即使应用程序处于不同的活动中,当前用户也为空 [英] Current User is Null even if the App is in a different Activity

查看:77
本文介绍了即使应用程序处于不同的活动中,当前用户也为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我再次面临空对象错误.我的应用程序编译正常,但在启动屏幕后,应用程序崩溃并显示我在此处发布的Logcat. 该错误发生在我的家庭活动中.有趣的是,在某些情况下,我的应用程序应该像正确运行一样,同时也正确放置了Common.currentUser.Name.这是在注册新用户后立即进行的,这意味着该代码正在运行.

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.

现在是我的问题;如何在HomeActivity中初始化当前用户?我相信我也需要一个 if (current user =null)语句. 我有一个UserModel类,其中保存了用户信息(当时可能为null),因此我将从Firebase数据库中加载用户信息. 我已经尝试过各种方法,但是我无法弄清楚该怎么做,也没有找到其他答案可以解决我的问题.

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.

也许有人也可以解释为什么当时不允许用户为空.初始屏幕后应该出现LoginActivity,因此即使我们不在HomeAtivity本身上,应用程序也会崩溃.我相信这与Common.class有关吗?!

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?!

感谢您的帮助.

我的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;
    }
}

我的HomeActivity.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.currentUsernull时执行的,因此会引发NullPointerException.有关更多信息,请参见什么是出色的解释. NullPointerException,该如何解决?

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?

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

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

如果您要在else块中实际设置 Common.currentUser,请不要忘记分配它.在这种情况下,代码可能是:

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

这篇关于即使应用程序处于不同的活动中,当前用户也为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆