-1

I am facing (again) a null object error. My App compiles just fine but after the splashscreen the App crashes with showing the Logcat I posted down there. The Error occurs in my Home Activity. The Interesting thing is that I had cases when the App was running like it should be with also putting the Common.currentUser.Name correctly. That was directly after the registration of a new user, which means the Code is working.

Now to my questions; How can I initialize the current User in my HomeActivity? I believe I also need a if (current user =null) statement. I have a UserModel class where User Information is saved(which could be null at that time) so I would load the User Information from my Firebase Database. I have tried out all kinds of things but I cannot figure out how to do that also I found no other question that answered my problem.

Maybe somebody can also explain why user is not allowed to be null at that time. After the Splash Screen should come the LoginActivity so even if we are not on the HomeAtivity itself the App crashes. I believe that has something to do with the Common.class?!

Any help is appreciated.

Part of my Common.class

    public static CategoryModel categorySelected;
    public static FoodModel selectedFood;
    public static String currentToken = "";
    public static String authorizeKey = "";


public static void setSpanString(String welcome, String name, TextView textView) {
        SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.append(welcome);
        SpannableString spannableString = new SpannableString(name);
        StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
        spannableString.setSpan(boldSpan, 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.append(spannableString);
        textView.setText(builder, TextView.BufferType.SPANNABLE);
    }

UserModel.class

public class UserModel {
    private String uid, name, address, phone, email, password;

    public UserModel() {
    }

    public UserModel(String uid, String name, String address, String phone,String email,String password) {
        this.uid = uid;
        this.name = name;
        this.address = address;
        this.phone = phone;
        this.email = email;
        this.password = password;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() { return password; }

    public void setPassword(String password) {
        this.password = password;
    }
}

part of my HomeActivity.java:Error occours in the last line

public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private AppBarConfiguration mAppBarConfiguration;
    private DrawerLayout drawer;
    private NavController navController;
    FirebaseAuth firebaseAuth;

    private CartDataSource cartDataSource;


    android.app.AlertDialog dialog;


    int menuClickId=-1;

    @BindView(R.id.fab)
    CounterFab fab;


    @Override
    protected void onResume() {
        super.onResume();
        countCartItem();
    }

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



        dialog = new SpotsDialog.Builder().setContext(this).setCancelable(false).build();

        ButterKnife.bind(this);

        cartDataSource = new LocalCartDataSource(CartDatabase.getInstance(this).cartDAO());


        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                navController.navigate(R.id.nav_cart);
            }
        });
        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_menu, R.id.nav_food_detail,
                R.id.nav_view_orders, R.id.nav_cart, R.id.nav_food_list)
                .setDrawerLayout(drawer)
                .build();
        navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
        navigationView.setNavigationItemSelectedListener(this);
        navigationView.bringToFront(); // Fixed


        View headerView = navigationView.getHeaderView(0);
        TextView txt_user = (TextView) headerView.findViewById(R.id.txt_user);

       if(currentUser!=null) {
            Common.setSpanString("Hey, ", currentUser.getName(), txt_user);
        }
        else{
            currentUser = new UserModel(uid,name,address,phone,email,password);
            currentUser.setName("Anonym");
            Common.setSpanString("Hey, ", name, txt_user);
            }

        }

Logcat

  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String edmt.dev.androideatitv2client.Model.UserModel.getName()' on a null object reference
        at edmt.dev.androideatitv2client.HomeActivity.onCreate(HomeActivity.java:131)
        at android.app.Activity.performCreate(Activity.java:6285)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
AnonRocketman
  • 178
  • 2
  • 16
  • 1
    `if(Common.currentUser!=null) ... else ... Common.currentUser.getName()` – Max Vollmer Dec 15 '19 at 15:20
  • 2
    Duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Max Vollmer Dec 15 '19 at 15:20
  • 1
    I have already tried that but it did not work out! Same error occours. Thanks anyways. – AnonRocketman Dec 15 '19 at 15:24
  • 1
    What do you mean by *"I have already tried that"*? I pointed out the problem in your code. You are accessing `currentUser` in `else`. – Max Vollmer Dec 15 '19 at 15:26

1 Answers1

3

As Max pointed out in the comments, you're accessing Common.currentUser.getName() in the else block. Since that block is executed when Common.currentUser is null, this raises a NullPointerException. For more in this, see the excellent explanation in What is a NullPointerException, and how do I fix it?

The solution is to not access Common.currentUser.getName() in the else block, but display the name from some other source. For example:

if(Common.currentUser!=null) {
    Common.setSpanString("Hey, ", Common.currentUser.getName(), txt_user);
}
else{
    UserModel userModel= new UserModel(uid,name,address,phone,email,password);
    userModel.setName("Anonym");
    Common.setSpanString("Hey, ", name, txt_user);
}

If you're trying to actually set the Common.currentUser in the else block, don't forget to assign it. In that case, the code could be:

if(Common.currentUser!=null) {
    Common.setSpanString("Hey, ", Common.currentUser.getName(), txt_user);
}
else{
    Commom.currentUser = new UserModel(uid,name,address,phone,email,password);
    Commom.currentUser.setName("Anonym");
    Common.setSpanString("Hey, ", Commom.currentUser.getName(), txt_user);
}

Or, if you simplify it a bit:

if(Common.currentUser == null) {
    Commom.currentUser = new UserModel(uid,name,address,phone,email,password);
    Commom.currentUser.setName("Anonym");
}
Common.setSpanString("Hey, ", Common.currentUser.getName(), txt_user);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 2
    I *believe* that `currentUser` is of type `UserModel` and OP tries to create a new instance of that class to use, but somehow got that wrong. Maybe update your answer to `currentUser = new UserModel(...);` That said, I think the question should be closed as duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) (disclaimer: downvote not from me) – Max Vollmer Dec 15 '19 at 15:32
  • 1
    While obviously OP is having a `NullPointException`, equally obviously they're unable to dig themselves out of the problem with just the linked question. This is made even clearer by the fact that they reposted the same [question](https://stackoverflow.com/q/59344410) a few hours earlier, with the same result. In such cases, I prefer showing OP exactly what to do, while still pointing out the nature of the NPE. When such an explanation doesn't fit in a comment (sometimes it does), I post it as an answer instead. If you disagree with this approach, feel free to open a meta about it. – Frank van Puffelen Dec 15 '19 at 16:02