-2

I have this error in Android Studio when I am trying to access ProfileFragment.I'm missing something, that's why I ask you to look over this. I want to mention that in User and UserAccountSetting classes are only Get and Set methods, to get and set all data member like name, description etc

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.food.User.User.getUsername()' on a null object reference
        at com.example.food.Utils.FirebaseMethods.getUserSettings(FirebaseMethods.java:274)
        at com.example.food.Profile.ProfileFragment$4.onDataChange(ProfileFragment.java:181)

My Firebase looks like this : enter image description here

and my FirebaseMethod looks like this :

 /* Retreive the accout settinigs for the user currlently logged in
     * Database:user"_account_settings node
     * @param dataSnapshot
     * @return
     */
    public UserSettings getUserSettings(DataSnapshot dataSnapshot){
        Log.d(TAG, "getUserAccountSettings: retrieving user account settings from firebase");

        UserAccountSettings settings = new UserAccountSettings();
        User user = new User();

        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            //user account settings node
            if (ds.getKey().equals(mContext.getString(R.string.dbname_user_account_settings))) {
                Log.d(TAG, "getUserAccountSettings: datasnapshot" + ds);

                try {
                    settings.setDisplay_name(
                            ds.child(userID)
                                    .getValue(UserAccountSettings.class)
                                    .getDisplay_name()
                    );
                    settings.setUsername(
                            ds.child(userID)
                                    .getValue(UserAccountSettings.class)
                                    .getUsername()
                    );
                    settings.setWebsite(
                            ds.child(userID)
                                    .getValue(UserAccountSettings.class)
                                    .getWebsite()
                    );
                    settings.setDescription(
                            ds.child(userID)
                                    .getValue(UserAccountSettings.class)
                                    .getDescription()
                    );
                    settings.setProfile_photo(
                            ds.child(userID)
                                    .getValue(UserAccountSettings.class)
                                    .getProfile_photo()
                    );
                    settings.setPosts(
                            ds.child(userID)
                                    .getValue(UserAccountSettings.class)
                                    .getPosts()
                    );
                    settings.setFollowing(
                            ds.child(userID)
                                    .getValue(UserAccountSettings.class)
                                    .getFollowing()
                    );
                    settings.setFollowers(
                            ds.child(userID)
                                    .getValue(UserAccountSettings.class)
                                    .getFollowers()
                    );
                } catch (NullPointerException e) {
                    Log.d(TAG, "getUserAccountSettings: NULLPointerException: " + e.getMessage());
                }
                Log.e(TAG, "getUserAccountSettings: retrieved user_account_settings information: " + settings.toString());

            }
            //users node
            if (ds.getKey().equals(mContext.getString(R.string.dbname_users))) {
                Log.d(TAG, "getUserAccountSettings: datasnapshot: " + ds);

                user.setUsername(
                        ds.child(userID)
                                .getValue(User.class) 
                                .getUsername() // here is line 274
                );
                user.setEmail(
                        ds.child(userID)
                                .getValue(User.class)
                                .getEmail()
                );
                user.setPhone_number(
                        ds.child(userID)
                                .getValue(User.class)
                                .getPhone_number()
                );
                user.setUser_id(
                        ds.child(userID)
                                .getValue(User.class)
                                .getUser_id()
                );

                Log.d(TAG, "getUserAccountSettings: retrieved users information: " + user.toString());
            }
        }
        return new UserSettings(user, settings);
    }

and ProfileFragment :

public class ProfileFragment extends Fragment {

    private static final String TAG = "ProfileFragment";

    private static final int ACTIVITY_NUM = 4;
    private TextView mPosts, mFollowers, mFollowing, mDisplayName, mUsername, mWebsite, mDescription;
    private CircleImageView mProfilePhoto;
    private GridView gridView;
    private Toolbar toolbar;
    private AppCompatButton profileMenu, chat, follow_button;
    private ChipNavigationBar chipNavigationBar;
    private Context mContext;

    //firebase
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;
    private FirebaseMethods mFirebaseMethods;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        mDisplayName = (TextView) view.findViewById(R.id.display_name);
        mUsername = (TextView) view.findViewById(R.id.username);
        mWebsite = (TextView) view.findViewById(R.id.website);
        mDescription = (TextView) view.findViewById(R.id.description);
        mProfilePhoto = (CircleImageView) view.findViewById(R.id.profile_photo);
        mPosts = (TextView) view.findViewById(R.id.tvPosts);
        mFollowers = (TextView) view.findViewById(R.id.tvFollowers);
        mFollowing = (TextView) view.findViewById(R.id.tvFollowing);
        gridView = (GridView) view.findViewById(R.id.gridView);
        toolbar = (Toolbar) view.findViewById(R.id.profileToolBar);
        profileMenu = (AppCompatButton) view.findViewById(R.id.buton_setari);
        chat = (AppCompatButton) view.findViewById(R.id.buton_mesaj);
        follow_button = (AppCompatButton) view.findViewById(R.id.buttonFollow);
        chipNavigationBar = (ChipNavigationBar) view.findViewById(R.id.navBar);
        mContext = getActivity();
        mFirebaseMethods = new FirebaseMethods(getActivity());
        Log.d(TAG, "onCreateView: started");


 private void setProfileWidgets(UserSettings userSettings){
        Log.d(TAG, "setProfileWidgets: setting widgets with data retrieving from firebase databse: " + userSettings.toString());


        UserAccountSettings settings = userSettings.getSettings();

        UniversalImageLoader.setImage(settings.getProfile_photo(), mProfilePhoto, null, "");

        mDisplayName.setText(settings.getDisplay_name());
        mUsername.setText(settings.getUsername());
        mWebsite.setText(settings.getWebsite());
        mDescription.setText(settings.getDescription());
    }

 private void setupFirebaseAuth(){

mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();

myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                //retrieve user info from database
                setProfileWidgets(mFirebaseMethods.getUserSettings(snapshot)); // here is line 181
                //retrieve image for the user in question
            }

            @Override
            public void onCancelled(DatabaseError error) {

            }
        });
    }

I looked over these too many times and I don't see anything wrong. Can you help me, please?:)

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Ac1234
  • 67
  • 6
  • 1
    Did you check the value of *userID*? Just to make sure it is something that you have in the db. – NiVeR Mar 20 '21 at 17:31
  • the userID is yUAKbXlq28hQI8ZjAXcQVYVcrSY2, right ?? Because I put a log.d in code, under for and this is what I got: USER ID 1UhgrHEtLUXR8eXdaYvIaTVTuO02 USER ID.child DataSnapshot { key = 1UhgrHEtLUXR8eXdaYvIaTVTuO02, value = null } the first one is only userID printed and the second is ds.child(userID) – Ac1234 Mar 20 '21 at 18:05
  • Did you make sure to not have spaces or any other strange characters? – NiVeR Mar 20 '21 at 18:16
  • where to check? – Ac1234 Mar 20 '21 at 18:19
  • Can you provide the outcome of log line: Log.d(TAG, "getUserAccountSettings: datasnapshot" + ds)? (for that particular record) – NiVeR Mar 20 '21 at 18:23
  • After you mention about stranger characters I checked the firebase authentication and there was the problem. Before, I tried to log in with google and the usedID was from there but google authentication doesn't work so I thought that I am not logged with google, just with email and password. Now I will try to understand why I cannot auth with google even the account is created. Thank you :) – Ac1234 Mar 20 '21 at 18:28

1 Answers1

0

In this code you are loading the entire database:

myRef = mFirebaseDatabase.getReference();
myRef.addValueEventListener(new ValueEventListener() {
  ...

But from looking at your getUserSettings method it is only expecting to get a snapshot of the JSON under /user_account_settings. So you should only be loading that data, which you can do with:

myRef = mFirebaseDatabase.getReference();
myRef.child("user_account_settings").addValueEventListener(new ValueEventListener() {
  ...
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807