从实时数据库中检索字符串到一个2D ArrayList中,Android。

huangapple go评论86阅读模式
英文:

Retrieve strings from real time database in a 2D ArrayList Android

问题

I have a Firebase Realtime Database structure like this:

如何将其检索为类似于以下的2D ArrayList,使用Java。

private String mChoices[][] = {
    {"Mutare", "Harare", "Bulawayo", "Mozambique"},
    {"Johannesburg", "Pretoria", "Durban", "Cape Town"},
    {"Nairobi", "Lusaka", "Windhoek", "Lilongwe"},
    {"Harare", "Lilongwe", "Pretoria", "Nairobi"}
};
英文:

I have a Firebase Realtime Database structure like this :

从实时数据库中检索字符串到一个2D ArrayList中,Android。

How do I retrieve it into a 2D ArrayList like this using Java.

private String mChoices [][] = {
        {"Mutare", "Harare", "Bulawayo","Mozambique"},
        {"Johhannesburg", "Pretoria", "Duran","Capetown"},
        {"Nairobi", "Lusaka", "Windhoek","Lilongwe"},
        {"Harare", "Lilongwe", "Pretoria","Nairobi"}
};

答案1

得分: 1

如@SardorbekKhujaev在他的回答中提到的,数组是固定的数据类型。为了解决这个问题,我们需要使用ArrayList,因为它的大小可以动态增加。一旦我们填充了ArrayList,我们可以简单地将它转换成一个二维数组,就像下面的代码行一样:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference choicesRef = rootRef.child("choices");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String[]> choices = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            int size = (int) ds.getChildrenCount();
            String[] choice = new String[size];
            int count = 0;
            for(DataSnapshot dSnapshot : ds.getChildren()) {
                choice[count++] = dSnapshot.getValue(String.class);
            }
            choices.add(choice);
        }
        String choicesArray[][] = new String[choices.size()][];
        for (int j = 0; j < choices.size(); j++) {
            choicesArray[j] = choices.get(j);
        }
        //测试数组
        for(String[] array : choicesArray) {
            Log.d(TAG, Arrays.toString(array));
        }
        //使用你的二维数组执行需要的操作
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //不要忽略潜在的错误!
    }
};
choicesRef.addListenerForSingleValueEvent(valueEventListener);

这段代码的结果将是你所需要的确切的二维数组。

英文:

As @SardorbekKhujaev mentioned in his answer, the arrays are fixed data-types. To solve the problem, we need to use an ArrayList, as the size can be increased dynamically. Once we populate the ArrayList we can simply convert it into an 2D array, like in the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference choicesRef = rootRef.child(&quot;choices&quot;);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List&lt;String[]&gt; choices = new ArrayList&lt;&gt;();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            int size = (int) ds.getChildrenCount();
            String[] choice = new String[size];
            int count = 0;
            for(DataSnapshot dSnapshot : ds.getChildren()) {
                choice[count++] = dSnapshot.getValue(String.class);
            }
            choices.add(choice);
        }
        String choicesArray[][] = new String[choices.size()][];
        for (int j = 0; j &lt; choices.size(); j++) {
            choicesArray[j] = choices.get(j);
        }
        //Test the array
        for(String[] array : choicesArray) {
            Log.d(TAG, Arrays.toString(array));
        }
        //Do what you need to do with your 2D array
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(&quot;TAG&quot;, databaseError.getMessage()); //Don&#39;t ignore potential errors!
    }
};
choicesRef.addListenerForSingleValueEvent(valueEventListener);

The result of this code will be the exact 2D array that you are looking for.

答案2

得分: 0

你正在要求使用一个二维数组,这会使代码变得更加复杂,因为数组不是动态的。考虑到Firebase数据是动态的,以及在Java中使用ArrayList的一般便利性,我建议你使用ArrayList。

这个解决方案专注于问题的核心 - 一个二维数组

private String[][] mChoices;
private void initializeMChoices(int i, int j) {
    mChoices = new String[i][j];
}

无论何时需要用String值填充数组请粘贴此代码

//获取对"choices"节点的引用:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("choices");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        //首先遍历整个节点以计算其子节点数
        int i = 0, j = 0;
        while(snapshot.child(Integer.toString(i)).exists())
        {
            j = 0;
            while(snapshot.child(Integer.toString(i)).child(Integer.toString(i)).exists())
            {
                j++;
            }
            i++;
        }
        //我们有了数字,现在我们初始化数组
        initializeMChoices(i, j);
        //遍历整个节点以将子节点的值放入二维数组
        i = 0;
        j = 0;
        while(snapshot.child(Integer.toString(i)).exists())
        {
            while(snapshot.child(Integer.toString(i)).child(Integer.toString(i)).exists())
            {
                j++;
                mChoices[i][j] = snapshot.child(Integer.toString(i)).child(Integer.toString(i)).toString();
            }
            i++;
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {

    }
});
英文:

You are asking to work with a 2D array, which makes the code more complex, as arrays are not dynamic. Taking into account that firebase data is dynamic and the general convenience of array lists in Java, I recommend you to use ArrayList.
This solution focuses on the matter of the question - a 2D array

private String[][] mChoices;
private void initializeMChoices(int i, int j) {
mChoices = new String[i][j];
}

Wherever you need to fill the array with the String values, paste this code:

        //Get the reference to the &quot;choices&quot; node:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(&quot;choices&quot;);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
// We first go through the whole node to count it&#39;s child nodes
int i = 0, j = 0;
while(snapshot.child(Integer.toString(i)).exists())
{
j = 0;
while(snapshot.child(Integer.toString(i)).child(Integer.toString(i)).exists())
{
j++;
}
i++;
}
// we have the numbers, now we initialize the array
initializeMChoices(i, j);
//we go through the whole node to put child-node values in the 2D array
i = 0;
j = 0;
while(snapshot.child(Integer.toString(i)).exists())
{
while(snapshot.child(Integer.toString(i)).child(Integer.toString(i)).exists())
{
j++;
mChoices[i][j] = snapshot.child(Integer.toString(i)).child(Integer.toString(i)).toString();
}
i++;
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});

huangapple
  • 本文由 发表于 2020年8月14日 15:00:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63408011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定