0

The database

I build an application and I'm trying to retrieve user info from Firebase. After the registration form, I have a new activity where the users need to write their personal info and that information is stored in firebase. Then, in my navigation drawer, I have an activity, called "AccountActivity", where the user cand see their personal info saved into the database. I tried to write some code in order to do this, but when I try to access the AccountActivity, it is empty..doesn't retrieve user info from firebase and I get this error:

SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero-length

Do you know what is wrong and what can I do in order to fix it?

This is the data I have in firebase, in JSON format, so the database is not empty:

  "User" : {
    "cgIW3VyfDONZjgA0r8LfGNr1zEO2" : {
      "age" : "30",
      "gender" : "Male",
      "height" : "170",
      "username" : "Alex",
      "weight" : "80"
    },
    "gLMP5YpLheQBWGxfyT5xcfOI9ii1" : {
      "age" : "28",
      "height" : "155",
      "username" : "Ana",
      "weight" : "60"
    }
  }
}

User class:


public class User {

    public String username;
    public String age;
    public String weight;
    public String height;
    public String gender;

    public User(){

    }

    public User(String username, String age, String weight, String height, String gender){

        this.username = username;
        this.age = age;
        this.weight = weight;
        this.height = height;
        this.gender = gender;

    }

    public String getUsername() {
        return username;
    }

    public String getAge() {
        return age;
    }

    public String getWeight() {
        return weight;
    }

    public String getHeight() {
        return height;
    }

    public String getGender() {
        return gender;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

AccountActivity:

public class AccountActivity extends AppCompatActivity {

    ListView myListView;
    ArrayAdapter<String> arrayAdapter;
    DatabaseReference databaseReference;
    FirebaseUser user;
    List<String> itemList;
    String userId;

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

        myListView = findViewById(R.id.listView);
        user = FirebaseAuth.getInstance().getCurrentUser();
        userId = user.getUid();
        itemList = new ArrayList<>();

         databaseReference = FirebaseDatabase.getInstance().getReference();
        userRef = databaseReference.child("User");
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    User user = ds.getValue(User.class);

                    itemList.add(user.getUsername());
                    itemList.add(user.getAge());
                    itemList.add(user.getWeight());
                    itemList.add(user.getHeight());
                    itemList.add(user.getGender());
                }
                arrayAdapter = new ArrayAdapter<>(AccountActivity.this, android.R.layout.simple_list_item_1, itemList);
                myListView.setAdapter(arrayAdapter);
            }

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

            }
        };
        userRef.addListenerForSingleValueEvent(valueEventListener);

activity_account.xml:

            android:id="@+id/textView"
            android:layout_width="263dp"
            android:layout_height="46dp"
            android:text="@string/account_informations"
            android:textColor="#FFFFFF"
            android:textSize="30sp"
            android:textStyle="bold|italic"
            app:fontFamily="@font/alex_brush"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <TextView
        android:id="@+id/tvUsernameDb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="178dp"
        android:layout_marginLeft="178dp"
        android:layout_marginTop="73dp"
        android:layout_marginEnd="175dp"
        android:layout_marginRight="175dp"
        android:layout_marginBottom="539dp"
        android:text="@string/textviewUsernameDb"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/constraintLayout" />

    <TextView
        android:id="@+id/tvAgeDb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="180dp"
        android:layout_marginLeft="180dp"
        android:layout_marginTop="51dp"
        android:layout_marginEnd="173dp"
        android:layout_marginRight="173dp"
        android:layout_marginBottom="468dp"
        android:text="@string/textviewAgeDb"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvUsernameDb" />

    <TextView
        android:id="@+id/tvWeightDb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="180dp"
        android:layout_marginLeft="180dp"
        android:layout_marginTop="47dp"
        android:layout_marginEnd="173dp"
        android:layout_marginRight="173dp"
        android:layout_marginBottom="402dp"
        android:text="@string/textviewWeightDb"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvAgeDb" />

    <TextView
        android:id="@+id/tvHeightDb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="181dp"
        android:layout_marginLeft="181dp"
        android:layout_marginTop="57dp"
        android:layout_marginEnd="171dp"
        android:layout_marginRight="171dp"
        android:layout_marginBottom="325dp"
        android:text="@string/textviewHeightDb"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvWeightDb" />

    <TextView
        android:id="@+id/tvGenderDb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="182dp"
        android:layout_marginLeft="182dp"
        android:layout_marginTop="54dp"
        android:layout_marginEnd="171dp"
        android:layout_marginRight="171dp"
        android:layout_marginBottom="252dp"
        android:text="@string/textviewGenderDb"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvHeightDb" />

In XML file, I put some text views, but with no text, just black space, and in string.xml I have something like this for each TextView form activity_account.xml: <string name="textviewGenderDb">" "</string>

So my questions are: I didn't something wrong in the XML file, or the code is written is wrong? I don't know where is the problem and why I get this error. Thanks for your help!

1 Answers1

0

I did something wrong in the XML file, or the code is written wrong?

There are three main problems.

  1. The fields in your User class are public. If you want to use getters and setters, make all of them private.

  2. Your databaseReference points to the root of your database but users are added within the User node. So in order to get all users, a call to .child("User") should be added. So please check the following lines of code:

    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference userRef = rootRef.child("User");
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                User user = ds.getValue(User.class);
                Log.d("TAG", user.getUsername());
            }
        }
    
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
        }
    };
    userRef.addListenerForSingleValueEvent(valueEventListener);
    

The result in the logcat will be:

Alex
Ana

Two thinks you should note. First, you can directly map a node from the database to a User object, without the need to create a new object and set the values. Second, the node should be more likely to be named Users or users and not simply User, because in that node exist multiple users and not a single one.

  1. Because you are iterating on a node that contains multiple users, you should use instead of TextView object a ListView. In this way you can add each details in a row.
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Thanks for your response! I made all the fields in my User class private, and now it retrieves me only the height of the user, without the other fields. It seems a little bit strange, because I implement the exact thing for the other fields. – Denisa Mărginean Jun 09 '20 at 11:43
  • I also tried your code and I will try to implement this with a ListView, maybe in this way it will show up all the fields stored in the database for the current user. – Denisa Mărginean Jun 09 '20 at 11:45
  • Please edit your question to also see a screenshot of your database, to be 100% sure. – Alex Mamo Jun 09 '20 at 11:54
  • Done. I added a screenshot of my database. – Denisa Mărginean Jun 09 '20 at 12:03
  • It's correct. It should work using a ListView. Give it a try and tell me if it works. – Alex Mamo Jun 09 '20 at 12:09
  • I tried with a ListView and still have the same problem: only the height is showed up.. – Denisa Mărginean Jun 09 '20 at 13:52
  • Edit your question with the changed code so I can take a look. – Alex Mamo Jun 09 '20 at 13:54
  • I edited the AccountActivity with the new code. I tried to implement this in two ways, but this is the final version, that retrieves me at least height. The first version of what I tried returned me into Logcot : ```empty item```, I don't know why. – Denisa Mărginean Jun 09 '20 at 14:00
  • Again, wrong reference. A call to `.child("User")` is mandatory. You are still creating an object of User class calling the constructor. Map it directly as in my answer. Get both lines `arrayAdapter = new ArrayAdapter<>(AccountActivity.this, android.R.layout.simple_list_item_1, itemList); myListView.setAdapter(arrayAdapter);` out of the loop and tell me if it works. – Alex Mamo Jun 09 '20 at 14:06
  • Ok, I changed AccountActivity considering your advices (I edited the question with the code) and now it retrieves me the height of all the users and nothing more. I am new to android studion and maybe I can see some obvious errors in my code or I don't know what's the thing with this problem – Denisa Mărginean Jun 09 '20 at 16:11
  • You are using a `List` in which you are adding all that `user.getUsername()`, `user.getAge()`, getWeight() etc. return. Your list should be of type `User`. So you need to add User object to the list. In the end, simply override toString() in your User class and display the desired data. – Alex Mamo Jun 09 '20 at 16:37
  • I made the list User type and override toString(), but is there something I should change at ```itemList.add(user.getUsername());``` etc and ```arrayAdapter = new ArrayAdapter<>(AccountActivity.this, android.R.layout.simple_list_item_1, itemList);``` ? because I have errors here, and if I solve the errors for ```itemList.add(user.getUsername());``` I get error in User class – Denisa Mărginean Jun 09 '20 at 18:27
  • The ArrayAdapter should also be of type User and when you add object to the list, add like this: `itemList.add(user);` – Alex Mamo Jun 09 '20 at 19:05
  • Now it retrieves me ``` null null null *height* null```, so all the params are null, except height – Denisa Mărginean Jun 09 '20 at 20:24
  • I will try to see where is the problem, maybe try another method – Denisa Mărginean Jun 09 '20 at 20:24
  • Without seeing the changed code, I cannot be much of a help. We usually stick to one question at a time but knowing that you are new to this, it's fine. So I hope you solved this issue. – Alex Mamo Jun 10 '20 at 08:48