0

I have faced a problem which are I attempt to invoke the null object reference but Im follow the video of Instagram Clone exactly, the video can done it without problem, but I get the problem, i had try so hard to find out the problem for an hour but I still didnt have any idea and I really tried all the solutions you proposed but it does not work for me.

here are the problem :

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.fivenine.shareit2.models.UserAccountSettings.getProfile_photo()' on a null object reference at com.fivenine.shareit2.ViewPostFragment.setupWidgets(ViewPostFragment.java:134) at com.fivenine.shareit2.ViewPostFragment.onCreateView(ViewPostFragment.java:98) at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460) at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852) at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802) at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625) at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411) at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273) at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733) at android.os.Handler.handleCallback(Handler.java:754) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:165) at android.app.ActivityThread.main(ActivityThread.java:6375) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)

Here are the code for UserAccountSettings:

public class UserAccountSettings {

private String description;
private String display_name;
private long followers;
private long following;
private long posts;
private String profile_photo;
private String username;
private String website;
private String user_id;

public UserAccountSettings(String description, String display_name, long followers, long following, long posts, String profile_photo, String username, String website, String user_id) {
    this.description = description;
    this.display_name = display_name;
    this.followers = followers;
    this.following = following;
    this.posts = posts;
    this.profile_photo = profile_photo;
    this.username = username;
    this.website = website;
    this.user_id = user_id;
}

public UserAccountSettings() {

}

public String getUser_id() {
    return user_id;
}

public void setUser_id(String user_id) {
    this.user_id = user_id;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getDisplay_name() {
    return display_name;
}

public void setDisplay_name(String display_name) {
    this.display_name = display_name;
}

public long getFollowers() {
    return followers;
}

public void setFollowers(long followers) {
    this.followers = followers;
}

public long getFollowing() {
    return following;
}

public void setFollowing(long following) {
    this.following = following;
}

public long getPosts() {
    return posts;
}

public void setPosts(long posts) {
    this.posts = posts;
}

public String getProfile_photo() {
    return profile_photo;
}

public void setProfile_photo(String profile_photo) {
    this.profile_photo = profile_photo;
}

public String getUsername() {
    return username;
}

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

public String getWebsite() {
    return website;
}

public void setWebsite(String website) {
    this.website = website;
}


@Override
public String toString() {
    return "UserAccountSettings{" +
            "description='" + description + '\'' +
            ", display_name='" + display_name + '\'' +
            ", followers=" + followers +
            ", following=" + following +
            ", posts=" + posts +
            ", profile_photo='" + profile_photo + '\'' +
            ", username='" + username + '\'' +
            ", website='" + website + '\'' +
            ", user_id='" + user_id + '\'' +
            '}';
}

}

and then it point out to the problem in ViewPostFragment, here are the code:

public class ViewPostFragment extends Fragment {

private static final String TAG = "ViewPostFragment";

public ViewPostFragment(){
    super();
    setArguments(new Bundle());
}

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


//widgets
private SquareImageView mPostImage;
private BottomNavigationViewEx bottomNavigationView;
private TextView mBackLabel, mCaption, mUsername, mTimestamp;
private ImageView mBackArrow, mEllipses, mHeartRed, mHeartWhite, mProfileImage;


//vars
private Photo mPhoto;
private int mActivityNumber = 0;
private String photoUsername = "";
private String profilePhotoUrl = "";
private UserAccountSettings mUserAccountSettings;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_view_post, container, false);
    mPostImage = (SquareImageView) view.findViewById(R.id.post_image);
    bottomNavigationView = (BottomNavigationViewEx) view.findViewById(R.id.bottomNavViewBar);
    mBackArrow = (ImageView) view.findViewById(R.id.backArrow);
    mBackLabel = (TextView) view.findViewById(R.id.tvBackLabel);
    mCaption = (TextView) view.findViewById(R.id.image_caption);
    mUsername = (TextView) view.findViewById(R.id.username);
    mTimestamp = (TextView) view.findViewById(R.id.image_time_posted);
    mEllipses = (ImageView) view.findViewById(R.id.ivEllipses);
    mHeartRed = (ImageView) view.findViewById(R.id.image_heart_red);
    mHeartWhite = (ImageView) view.findViewById(R.id.image_heart);
    mProfileImage = (ImageView) view.findViewById(R.id.profile_photo);

    try{
        mPhoto = getPhotoFromBundle();
        UniversalImageLoader.setImage(mPhoto.getImage_path(), mPostImage, null, "");
        mActivityNumber = getActivityNumFromBundle();

    }catch (NullPointerException e){
        Log.e(TAG, "onCreateView: NullPointerException: " + e.getMessage() );
    }

    setupFirebaseAuth();
    setupBottomNavigationView();
    getPhotoDetails();
    setupWidgets();

    return view;
}

private void getPhotoDetails(){
    Log.d(TAG, "getPhotoDetails: retrieving photo details.");
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
    Query query = reference
            .child(getString(R.string.dbname_user_account_settings))
            .orderByChild(getString(R.string.field_user_id))
            .equalTo(mPhoto.getUser_id());
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for ( DataSnapshot singleSnapshot :  dataSnapshot.getChildren()){
                mUserAccountSettings = singleSnapshot.getValue(UserAccountSettings.class);
            }
            //setupWidgets();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d(TAG, "onCancelled: query cancelled.");
        }
    });
}

private void setupWidgets() {
    String timestampDiff = getTimestampDifference();
    if (!timestampDiff.equals("0")) {
        mTimestamp.setText(timestampDiff + " DAYS AGO");
    } else {
        mTimestamp.setText("TODAY");
    }

        UniversalImageLoader.setImage(mUserAccountSettings.getProfile_photo(), mProfileImage, null, "");
        mUsername.setText(mUserAccountSettings.getUsername());


}
/**
 * Returns a string representing the number of days ago the post was made
 * @return
 */
private String getTimestampDifference(){
    Log.d(TAG, "getTimestampDifference: getting timestamp difference.");

    String difference = "";
    Calendar c = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.CANADA);
    sdf.setTimeZone(TimeZone.getTimeZone("Canada/Pacific"));//google 'android list of timezones'
    Date today = c.getTime();
    sdf.format(today);
    Date timestamp;
    final String photoTimestamp = mPhoto.getDate_created();
    try{
        timestamp = sdf.parse(photoTimestamp);
        difference = String.valueOf(Math.round(((today.getTime() - timestamp.getTime()) / 1000 / 60 / 60 / 24 )));
    }catch (ParseException e){
        Log.e(TAG, "getTimestampDifference: ParseException: " + e.getMessage() );
        difference = "0";
    }
    return difference;
}

/**
 * retrieve the activity number from the incoming bundle from profileActivity interface
 * @return
 */
private int getActivityNumFromBundle(){
    Log.d(TAG, "getActivityNumFromBundle: arguments: " + getArguments());

    Bundle bundle = this.getArguments();
    if(bundle != null) {
        return bundle.getInt(getString(R.string.activity_number));
    }else{
        return 0;
    }
}

/**
 * retrieve the photo from the incoming bundle from profileActivity interface
 * @return
 */
private Photo getPhotoFromBundle(){
    Log.d(TAG, "getPhotoFromBundle: arguments: " + getArguments());

    Bundle bundle = this.getArguments();
    if(bundle != null) {
        return bundle.getParcelable(getString(R.string.photo));
    }else{
        return null;
    }
}

/**
 * BottomNavigationView setup
 */
private void setupBottomNavigationView(){
    Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
    BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationView);
    BottomNavigationViewHelper.enableNavigation(getActivity(),getActivity() ,bottomNavigationView);
    Menu menu = bottomNavigationView.getMenu();
    MenuItem menuItem = menu.getItem(mActivityNumber);
    menuItem.setChecked(true);
}

   /*
------------------------------------ Firebase ---------------------------------------------
 */

/**
 * Setup the firebase auth object
 */
private void setupFirebaseAuth(){
    Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");

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

    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");
            }
            // ...
        }
    };


}


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

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

}

and it seems like this line causing problem:

UniversalImageLoader.setImage(mUserAccountSettings.getProfile_photo(), mProfileImage, null, "");
            mUsername.setText(mUserAccountSettings.getUsername()); 
EeHang Tang
  • 9
  • 1
  • 4

1 Answers1

0

You are getting null value from singleSnapshot.getValue(UserAccountSettings.class).

You need to check the available data at the reference, you have added your your listenerForSingleValueEvent on, in your Firebase database.

Manishoaham
  • 366
  • 3
  • 11