[Solved] How to loop on an android View to add a text from database?


What it looks like right now is that you end up with just having 71008 in your first TextView because you loop through the keys but only ever access the first TextView.

If you know that you’ll always have eight keys, in your case you can try adding them to your TextViews without the loop, something along the lines of:

// Read from the database
mRootReference.addListenerForSingleValueEvent (new ValueEventListener() { 
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        // This method is called once with the initial value and again
        // whenever data at this location is updated.
        Iterator<DataSnapshot> children = dataSnapshot.getChildren().iterator(); 

        mRolll.setText(children.next().getKey());
        mRoll2.setText(children.next().getKey());
        mRoll3.setText(children.next().getKey());
        mRoll4.setText(children.next().getKey());
        mRoll5.setText(children.next().getKey());
        mRoll6.setText(children.next().getKey());
        mRoll7.setText(children.next().getKey());
        mRoll8.setText(children.next().getKey());
    }
    @Override
    public void onCancelled(@NonNull DatabaseError error) { 
        //Failed to read value
    }
});

If you want to use a loop, I would recommend placing your TextViews in an Array or List and then looping through those with the children:

// Read from the database
mRootReference.addListenerForSingleValueEvent (new ValueEventListener() { 
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        // This method is called once with the initial value and again
        // whenever data at this location is updated.
        Iterator<DataSnapshot> children = dataSnapshot.getChildren().iterator(); 

        TextView[] views = new TextView[] {
            mRolll,
            mRoll2,
            mRoll3,
            mRoll4,
            mRoll5,
            mRoll6,
            mRoll7,
            mRoll8,
        }

        for (int i = 0; i < views.length && children.hasNext(); i++) {
            views[i].setText(children.next().getKey());
        }
    }
    @Override
    public void onCancelled(@NonNull DatabaseError error) { 
        //Failed to read value
    }
});

(The Array could be created elsewhere, probably in the same place you instantiate your Views)

2

solved How to loop on an android View to add a text from database?