空ArrayList-Firebase数据检索 [英] Empty ArrayList - Firebase Data Retrieval

查看:76
本文介绍了空ArrayList-Firebase数据检索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在Firebase数据库上运行查询,我可以在日志中看到所需的值,但是我的方法始终返回一个空的数组列表.

I am currently trying to run a query on my firebase DB, I can see the values that I want in my logs but my method always returns an empty arraylist.

请在下面找到我的代码:

Kindly find my code below:

public static ArrayList<Transaction> getUserTransactions(String userId){
    Query userTransactionQuery = mDatabaseReference
            .child("transactions")
            .orderByChild("userId")
            .equalTo(userId);

    final ArrayList<Transaction> transactionsByUser = new ArrayList<>();

    userTransactionQuery.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot transactionSnapshot: dataSnapshot.getChildren()) {
                // TODO: handle the post
                Transaction t = transactionSnapshot.getValue(Transaction.class);
                transactionsByUser.add(t);
                Log.w(TAG, t.toString());
            }

            Log.i(TAG, "Collected User Transactions");
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            // Getting Transaction failed, log a message
            Log.w(TAG, "loadTransactions:onCancelled", databaseError.toException());
            // ...
        }
    });

    return transactionsByUser;
}

我的POJO:

public class Transaction {
    private String id;

    private String userId;

    private String categoryId;

    private TransactionType transactionType;

    private String creationDate;

    private long amount;

    private String description;
    /**
     * No args constructor
     */
    public Transaction () {}


    /**
     * Constructor for the Transaction object
     * @param userId id of the user who made the transaction
     * @param categoryId ID of the category the transaction belongs under
     * @param amount amount spent/received
     * @param transactionType income/expense
     */
    public Transaction(String userId, String categoryId, TransactionType transactionType, long amount, String description) {
        this.userId = userId;
        this.categoryId = categoryId;
        this.transactionType = transactionType;
        this.amount = amount;

        this.description = description;

        //Date last changed will always be set to ServerValue.TIMESTAMP
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String currentDateTime = dateFormat.format(new Date()); // Find todays date

        this.creationDate = currentDateTime;
    }

    /**
     * Transaction Id Getter
     * @return transaction Id
     */
    public String getId() {
        return id;
    }

    /**
     * Transaction Id Setter
     * @param id Id to assign to the user
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * Category Id getter
     * @return category Id under which the transaction belongs
     */
    public String getCategoryId() {
        return categoryId;
    }

    /**
     * Category Id setter
     * @param categoryId  category Id under which the transaction belongs
     */
    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId;
    }

    /**
     * Transaction type getter
     * @return type of the transaction whether its an income or an expense
     */
    public TransactionType getTransactionType() {
        return transactionType;
    }

    /**
     * Transaction type setter
     * @param transactionType type of the transaction to set
     */
    public void setTransactionType(TransactionType transactionType) {
        this.transactionType = transactionType;
    }

    /**
     * Transaction creation date getter
     * @return creation date of the transaction
     */
    public String getCreationDate() {
        return creationDate;
    }

    /**
     * Transaction creation date setter
     * @param creationDate creation date to set to the transaction
     */
    public void setCreationDate(String creationDate) {
        this.creationDate = creationDate;
    }

    /**
     * Transaction amount getter
     * @return amount set
     */
    public long getAmount() {
        return amount;
    }

    /**
     * Transaction amount setter
     * @param amount amount to set
     */
    public void setAmount(long amount) {
        this.amount = amount;
    }

    /**
     * User Id getter
     * @return user id corresponding to the transaction
     */
    public String getUserId() {
        return userId;
    }

    /**
     * User Id setter
     * @param userId user id to set to the transaction
     */
    public void setUserId(String userId) {
        this.userId = userId;
    }

    /**
     * Description getter
     * @return Description corresponding to the transaction
     */
    public String getDescription() {
        return description;
    }
    /**
     * Description setter
     * @param description Description to set to the transaction
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * Transaction object string representation
     * @return object represented in a string
     */
    @Override
    public String toString() {
        return "Transaction{" +
                "id='" + id + '\'' +
                ", userId='" + userId + '\'' +
                ", categoryId='" + categoryId + '\'' +
                ", transactionType=" + transactionType +
                ", creationDate='" + creationDate + '\'' +
                ", amount=" + amount +
                '}';
    }
}

我的JSON树如下:

{
  transactions:
    {
      transactionId {
        pojo
      }
  }        
}

简而言之:我要做的是使用用户ID来获取用户进行的所有交易,我试图将结果存储在数组列表中,但数组列表始终返回空;

In brief: what I'm trying to do is get all the transactions made by a user using his user ID, Im trying to store the result in an array list but the array list always returns empty;

推荐答案

因此,这只是尝试回答您的问题:

So this is just an attempt to answer your question:

public static void getUserTransactions(String userId, final ArrayList<Transaction> transactionsByUser){
Query userTransactionQuery = mDatabaseReference
        .child("transactions")
        .orderByChild("userId")
        .equalTo(userId);

userTransactionQuery.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot transactionSnapshot: dataSnapshot.getChildren()) {
            // TODO: handle the post
            Transaction t = transactionSnapshot.getValue(Transaction.class);
            transactionsByUser.add(t);
            Log.w(TAG, t.toString());
        }

        Log.i(TAG, "Collected User Transactions");
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Getting Transaction failed, log a message
        Log.w(TAG, "loadTransactions:onCancelled", databaseError.toException());
        // ...
    }
});
}

用法

ArrayList<Transaction> transactions = new ArrayList<>();

getUserTransactions("{userId}", transactions);

//check after method call while debugging if transactions is empty

如果这不起作用,则必须在使用ArrayList的地方使用此事件实现.请注意,Firebase查询是异步的.

If this does not work you going to have to use this event implementation where the ArrayList is being used. Be aware that Firebase queries are asynchronous.

这篇关于空ArrayList-Firebase数据检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆