0

How would I achieve the retrieval of account based arrays, Currently when I run the following code it doesn't retrieve anything. I'm a complete beginner and I tried looking at other examples but mine are different to others. My goal is to retrieve all the arrays belonging to that user. For now I just want to return the names of these items but later I want to to use the array also, So the first user would have:

Fruit = ["apple", "banana", "mango" ]
Veg = ["tomato", "potato", "cabbage" ]

Code:

public class HomeActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{

private ZXingScannerView scannerView;
private final int permission_code = 1;

String [] selectedProfile;
Spinner spinner;
ArrayAdapter<CharSequence> adapter;

ListView lvProfiles;


private String userID;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    mAuth = FirebaseAuth.getInstance();
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference();
    FirebaseUser user = mAuth.getCurrentUser();
    userID = user.getUid();

    if(mAuth.getCurrentUser() == null){
        finish();
        startActivity(new Intent(this, MainActivity.class));
    }

    startSpinner();

    lvProfiles = (ListView)findViewById(R.id.lvProfiles);

    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            showData(dataSnapshot);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

private void showData(DataSnapshot dataSnapshot) {
    for(DataSnapshot ds : dataSnapshot.getChildren()){
        String x = ds.child("users").child(userID).getValue(String.class);

        ArrayList<String> array  = new ArrayList<>();
        array.add(x);
        ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
        lvProfiles.setAdapter(adapter);
    }
}

My database looks like so:

{
  "users" : {

"9kV3otdvOXU0CGMZWIIxggrBrj63" : {

  "Fruit" : [ "apple", "banana", "mango" ],
  "Veg" : [ "tomato", "potato", "cabbage" ]
},
"FKazRnUjrzMuQs6dbeIIGaGju5W2" : {

  "Gluten" : [ "123", "456", "789" ]
},
"xaLZIfNudthJ8BuY6WBqYrrYPsA2" : {

  "Berries" : [ "strawberry", "raspberry", "blackberry", "blueberry", "gooseberry" ],
  "Cheese" : [ "feta", "mozzarella", "cheddar" ],
  "Kiwi" : [ "kiwi" ]
}
  }
}

Update: I changed as you suggested but "fruit" and "veg" don't appear in the spinner, could you suggest anything? here is the new code.

private void showData(DataSnapshot dataSnapshot) {

    Map<String,Object> map = dataSnapshot.child("users").child(userID).getValue(Map.class);
    ArrayList<String> array  = new ArrayList<>();
    for (Map.Entry<String,Object> entry : map.entrySet()) {

        // key contains "Fruit" or "Veg"
        String key = entry.getKey();
        // value is the corresponding list
        Object value = entry.getValue();
        array.addAll((ArrayList) value);

    }
    ArrayAdapter adapterUser = new ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
    spinnerUser.setAdapter(adapterUser);

}

Rules:

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}
2
  • A separate issue, user.getUid() is called before user is checked to be null. Looks like you have a null pointer exception in your future. Commented Feb 12, 2018 at 22:34
  • Also, point database references to the specific location at initialization, dont just point to root or "users" or else you grab everything. Don't initialize arraylists in a loop, the arraylist will be emptied and recreated every iteration. When using listview type items like spinners, do the adapter stuff in oncreate, then when you fill your "array" variable, call adapter.notifyDataSetChanged(); or else you make the system recreate the adapter object every time you call showData. Commented Feb 12, 2018 at 23:18

1 Answer 1

1

There are a number of things that are convoluted and probably aren't accomplishing what you want. I think you are looking for something that returns a map of lists per a specific user, then collects all of the list items into a spinner. If so, try this

private void showData(DataSnapshot dataSnapshot) {

   Map<String,Object> map = (Map) dataSnapshot.getValue().child("users").child(userID);
   ArrayList<String> array  = new ArrayList<>();
   for (Map.Entry<String, Object> entry : map.entrySet()) {

      // key contains "Fruit" or "Veg"
      String key = entry.getKey();
      // value is the corresponding list
      Object value = entry.getValue();
      array.addAll((ArrayList) value);

   }
   ArrayAdapter adapter = new 
       ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
   lvProfiles.setAdapter(adapter);

}

I wasn't able to test this so try it, let me know what errors occur and I will edit the answer accordingly.

Sign up to request clarification or add additional context in comments.

19 Comments

Hi ryan, thanks for that, I get an error here: Map map = dataSnapshot.child("users").child(userID).getValue(Map.class); ArrayList<String> array = new ArrayList<>(); for (Map.Entry<String, Object> entry : map.entrySet()) { 3rd line says "incompatible types, required object, found <string,object>
(Map.Entry<String, Object> entry "incompatible types, required object, found <string,object>
Change "Map map = " to "Map<String,Object> map = ".
Anything or just fruit and veg?
Thank you I hope everything works out for you in life.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.