Java 即使应用程序处于不同的活动中,当前用户也为空

Java 即使应用程序处于不同的活动中,当前用户也为空,java,android,firebase,firebase-realtime-database,Java,Android,Firebase,Firebase Realtime Database,我(再次)面临一个空对象错误。我的应用程序编译得很好,但是在splashscreen之后,应用程序崩溃了,显示了我在下面发布的日志。 错误发生在我的家庭活动中。有趣的是,当应用程序正常运行时,我遇到过这样的情况,并且正确地放置了Common.currentUser.Name。这是在新用户注册之后,这意味着代码正在工作 现在回答我的问题;如何在HomeActivity中初始化当前用户?我相信我也需要一个 if(当前用户=null)语句。 我有一个UserModel类,其中保存了用户信息(当时可能为

我(再次)面临一个空对象错误。我的应用程序编译得很好,但是在splashscreen之后,应用程序崩溃了,显示了我在下面发布的日志。 错误发生在我的家庭活动中。有趣的是,当应用程序正常运行时,我遇到过这样的情况,并且正确地放置了Common.currentUser.Name。这是在新用户注册之后,这意味着代码正在工作

现在回答我的问题;如何在HomeActivity中初始化当前用户?我相信我也需要一个
if(当前用户=null)
语句。 我有一个UserModel类,其中保存了用户信息(当时可能为null),因此我将从Firebase数据库加载用户信息。 我已经尝试了各种各样的方法,但我不知道如何去做,而且我也没有找到其他问题来回答我的问题

也许有人可以解释为什么用户在那个时候不允许为null。启动屏幕之后应该是LoginActivity,因此即使我们不在HomeActivity上,应用程序也会崩溃。我相信这和普通人有关。阶级

感谢您的帮助

我的普通课程的一部分

    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);
    }
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;
    }
}
UserModel.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);
    }
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;
    }
}
我的家庭活动的一部分。java:最后一行出现错误

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)

正如Max在评论中指出的,您正在访问
else
块中的
Common.currentUser.getName()
。由于该块是在
Common.currentUser
null
时执行的,因此会引发
NullPointerException
。有关这方面的更多信息,请参见中的精彩解释

解决方案是在
else
块中not访问
Common.currentUser.getName()
,但显示来自其他源的名称。例如:

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);
}
如果您试图在
else
块中实际设置
Common.currentUser
,请不要忘记分配它。在这种情况下,代码可以是:

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);
}
或者,如果你稍微简化一下:

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);

if(Common.currentUser!=null)。。。其他的Common.currentUser.getName()
Duplicate of我已经尝试过了,但是没有成功!同样的错误也发生了。谢谢,你说“我已经试过了”是什么意思?我指出了代码中的问题。您正在访问
else
中的
currentUser
。我认为
currentUser
属于
UserModel
类型,OP试图创建该类的新实例以供使用,但不知怎的,它错了。可能会将您的答案更新为
currentUser=newusermodel(…)
也就是说,我认为这个问题应该以重复的形式结束(免责声明:downvote不是我提出的),而OP显然有一个
NullPointException
,同样明显的是,他们无法用链接的问题来解决问题。这一点更为清楚,因为他们在几小时前重新发布了同样的消息,结果也是一样的。在这种情况下,我更喜欢向OP展示确切的操作,同时仍然指出NPE的本质。如果这样的解释不适合评论(有时是这样),我会将其作为答案发布。如果您不同意这种方法,请随意打开一个元数据。