0

enter image description hereIn my application I have allowed my users to save their details into the firebase database I was then trying to allow the users to view their details in a ListView.

    package com.example.aaron.inthehole;


import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
public class view_database extends AppCompatActivity {
    private static final String TAG = "ViewDatabase";

    //add Firebase Database stuff
    private FirebaseDatabase mFirebaseDatabase;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private DatabaseReference myRef;
    private  String userID;

    private ListView mListView;

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

        mListView = (ListView) findViewById(R.id.listview);

        //declare the database reference object. This is what we use to access the database.
        //NOTE: Unless you are signed in, this will not be useable.
        mAuth = FirebaseAuth.getInstance();
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        myRef = mFirebaseDatabase.getReference();
        FirebaseUser user = mAuth.getCurrentUser();
        assert user != null;
        userID = user.getUid();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
                    toastMessage("Successfully signed out.");
                }
                // ...
            }
        };

        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()){
            UserInformation uInfo = new UserInformation();
            uInfo.setName(ds.child(userID).getValue(UserInformation.class).getName()); //set the name
            uInfo.setHandicap(ds.child(userID).getValue(UserInformation.class).getHandicap()); //set the name
            uInfo.setAge(ds.child(userID).getValue(UserInformation.class).getAge()); //set the email
            uInfo.setGender(ds.child(userID).getValue(UserInformation.class).getGender()); //set the phone_num

            //display all the information
            Log.d(TAG, "showData: name: " + uInfo.getName());
            Log.d(TAG, "showData: age: " + uInfo.getAge());
            Log.d(TAG, "showData: handicap: " + uInfo.getHandicap());
            Log.d(TAG, "showData: gender: " + uInfo.getGender());

            ArrayList<String> array  = new ArrayList<>();
            array.add("Full Name:");
            array.add(uInfo.getName());
            array.add("Age:");
            array.add(uInfo.getAge());
            array.add("Handicap:");
            array.add(uInfo.getHandicap());
            array.add("Gender:");
            array.add(uInfo.getGender());
            ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
            mListView.setAdapter(adapter);
        }
    }
    */
    private void showData(DataSnapshot dataSnapshot) {
        ArrayList<String> array  = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()){
            UserInformation uInfo = ds.getValue(UserInformation.class);
            array.add(uInfo.getName() + " / " + uInfo.getAge());


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

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }


    /**
     * customizable toast
     * @param message
     */
    private void toastMessage(String message){
        Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
    }
}

public class UserInformation {

private String name;
private String age;
private String gender;
private String handicap;

public UserInformation(){

}

public String getAge() {
    return age;
}

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

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getGender() {
    return gender;
}

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

public void setHandicap(String handicap) {
    this.handicap = handicap;
}

} When I run my application and enter the view details page an error occurs and in the run a message comes up saying:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.aaron.inthehole, PID: 8958
                  java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.aaron.inthehole.UserInformation.getName()' on a null object reference
                      at com.example.aaron.inthehole.view_database.showData(view_database.java:94)
                      at com.example.aaron.inthehole.view_database.access$100(view_database.java:31)
                      at com.example.aaron.inthehole.view_database$2.onDataChange(view_database.java:80)
                      at com.google.android.gms.internal.zzegf.zza(Unknown Source:13)
                      at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source:2)
                      at com.google.android.gms.internal.zzeig.run(Unknown Source:65)
                      at android.os.Handler.handleCallback(Handler.java:790)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6494)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

This is the part of my applications where the details are stored

String name1 = name.getText().toString();
                String handicap1 = handicap.getText().toString();
                String age1 = age.getText().toString();
                String gender1 = gender.getText().toString();
                String user_id = mAuth.getCurrentUser().getUid();
                DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
                Map newPost = new HashMap();
                newPost.put("name",name1);
                newPost.put("handicap",handicap1);
                newPost.put("age",age1);
                newPost.put("gender",gender1);
                current_user_db.setValue(newPost);
                Toast.makeText(ProfileActivity.this, "Details Saved", Toast.LENGTH_SHORT).show();
Aaron Nicholl
  • 121
  • 2
  • 9

2 Answers2

0

Just add if(dataSnapshot.exists())

if(dataSnapshot.exists())
{
UserInformation uInfo = new UserInformation();
            uInfo.setName(ds.child(userID).getValue(UserInformation.class).getName()); //set the name
            uInfo.setHandicap(ds.child(userID).getValue(UserInformation.class).getHandicap()); //set the name
            uInfo.setAge(ds.child(userID).getValue(UserInformation.class).getAge()); //set the email
            uInfo.setGender(ds.child(userID).getValue(UserInformation.class).getGender()); //set the phone_num
}
0

According to your edited post, to solve this, please do the following changes. First change the following line of code:

myRef = mFirebaseDatabase.getReference();

with

myRef = mFirebaseDatabase.getReference().child("Users");

Your code can be reduces only to a few lines of code like this:

private void showData(DataSnapshot dataSnapshot) {
    ArrayList<String> array  = new ArrayList<>();
    for(DataSnapshot ds : dataSnapshot.getChildren()){
        UserInformation uInfo = ds.getValue(UserInformation.class);
        array.add(uInfo.getName() + " / " + uInfo.getAge());

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

You have two major problems in your code. You are creating a new instance of UserInformation class instead of getting one from the database. And second, you are creating a new list and you are setting the adapter on every iteration. So as you can see, I have moved those lines of code outside that loop.

And for the current authenticated user, please change the following line:

myRef = mFirebaseDatabase.getReference().child("Users");

with:

myRef = mFirebaseDatabase.getReference().child("Users").child(userID);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • **[Here](https://stackoverflow.com/questions/49383687/how-can-i-retrieve-data-from-firebase-to-my-adapter/49384849)** can you also see the steps that you can follow if you want to display data in a RecyclerView using a RecyclerViewAdapter. – Alex Mamo Mar 20 '18 at 14:34
  • The array now responds with a null/ null in my listview – Aaron Nicholl Mar 22 '18 at 17:23
  • Please edit your question by adding the code that it wrote too see more clearly where the problem is. – Alex Mamo Mar 23 '18 at 09:26
  • Please also add your database structure. I think is something about the references. – Alex Mamo Mar 23 '18 at 10:54
  • I have added where the details are stored – Aaron Nicholl Mar 23 '18 at 12:52
  • Yes it brings up details but is there a way to edit it that it only brings ups the current users details? – Aaron Nicholl Mar 23 '18 at 17:24
  • I changed the myRef = mFirebaseDatabase.getReference().child("Users"); – Aaron Nicholl Mar 23 '18 at 17:36
  • with String uid = FirebaseAuth.getInstance().getCurrentUser().getUid(); myRef = mFirebaseDatabase.getReference().child("Users").child(uid); and it doesn't work lol – Aaron Nicholl Mar 23 '18 at 17:36
  • Please see again my updated answer. Is should be `userID`. You already have that id. – Alex Mamo Mar 23 '18 at 17:40
  • FATAL EXCEPTION: main Process: com.example.aaron.inthehole, PID: 18998 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aaron.inthehole/com.example.aaron.inthehole.view_database}: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child() – Aaron Nicholl Mar 23 '18 at 18:06
  • it means that the the user id that comes from the auth object is `null`. Make sure is not `null`. – Alex Mamo Mar 23 '18 at 18:07
  • When a user registers with the application they are each given a User UID. This UID is not stored in the Users table. Is there a way to use this value to check for current user? – Aaron Nicholl Mar 23 '18 at 18:30
  • Yes, by adding that user id in as the key and then use exists() method directly on the `DatabaseReference` object. – Alex Mamo Mar 24 '18 at 07:37