设置默认值但结果为null

时间:2017-12-30 02:40:14

标签: java android firebase firebase-realtime-database

将费率设置为默认值=“0”但结果为空。费率的价值(费率加到Rider.class)不会像Firebase那样添加到Firebase中的表格中......

任何想法如何解决都将非常感谢....

nav_header_home

<TextView
            android:id="@+id/txtStars"
            android:text="4"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />

// properties:
Textview txtStars;

// onCreate:
View navigationHeaderView = navigationView.getHeaderView(0);
txtStars = navigationHeaderView.findViewById(R.id.txtStars);
txtStars.setText(String.format("%s", Common.currentUser.getRates()));

MainActivity

// showRegisterDialog() ...

// Register new user
            auth.createUserWithEmailAndPassword(edtEmail.getText().toString(),
                    edtPassword.getText().toString())
                    .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                        @Override
                        public void onSuccess(AuthResult authResult) {
                            // Save user to db
                            Rider rider = new Rider();
                            rider.setRates("0");//<---- default value

Home.java

    @SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_signOut) {
        signOut();

    } else if (id == R.id.nav_updateInfo) {
        showUpdateInfoDialog();
    }

    return true;
}

在AutoLogin方法的 MainActivity 中.... (因为它有自动登录),也不得不添加;

 // fetch data an save to variable
                    FirebaseDatabase.getInstance().getReference(Common.user_rider_tbl)
                            .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                            .addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(DataSnapshot dataSnapshot) {
                                    Common.currentUser = dataSnapshot.getValue(Rider.class);

                                    waitingDialog.dismiss();

                                    Intent i = new Intent(RiderActivity.this,
                                            Home.class);
                                    startActivity(i);
                                    finish();
                                }

                                @Override
                                public void onCancelled(DatabaseError databaseError) {}
                            });

调试时,txtStars = null

1 个答案:

答案 0 :(得分:3)

如果要将速率的默认值设置为零,那么在初始化变量时,我只需将该值设置为零。

private String rates = "0";

或者您可以在构造函数中设置默认值,如下所示:

public Rider() {this.rates = "0";}

这样,费率的价值总是会有一个默认值为零,让我知道这是怎么回事! :)