2016-10-05 6 views
0

なぜuserId文字列が返ってくるのか分かりませんnull。助けてください。if文でもnullに戻るユーザ

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    //get firebase auth instance 
    auth = FirebaseAuth.getInstance(); 
    mDatabaseReference = FirebaseDatabase.getInstance().getReference(); 
    Intent intent = getIntent(); 
    carName = intent.getStringExtra("carname"); 

    //get current user 
    if (auth.getCurrentUser().getUid() != null) { 
     userId = auth.getCurrentUser().getUid(); 
    } 
    authStateListener = new FirebaseAuth.AuthStateListener() { 
     @Override 
     public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 
      FirebaseUser user = firebaseAuth.getCurrentUser(); 
      if (user != null) { 
       Log.d(TAG, "AUTH STATE SIGNED IN"); 
       userId = user.getUid(); 
       getCarName(); 
       mDatabaseReference.child("cars").setValue(userId); 
      } else { 
       //User is Signed out 
       Log.d(TAG, "AUTH STATE SIGNED OUT"); 
       startActivity(new Intent(MainActivity.this, LoginActivity.class)); 
      } 
     } 
    }; 
    auth.addAuthStateListener(authStateListener); 

    //set views 
    setContentView(R.layout.activity_main); 
    final TextView carNameTV = (TextView) findViewById(R.id.car_name); 
    final TextView carAddressTV = (TextView) findViewById(R.id.car_notes); 
    final TextView carCountTV = (TextView) findViewById(R.id.count); 
    plusOneButton = (Button) findViewById(R.id.buttonIn); 
    minusOneButton = (Button) findViewById(R.id.buttonOut); 
    signOut = (Button) findViewById(R.id.sign_out_button); 
    editCar = (Button) findViewById(R.id.edit_car_button); 



    mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("cars").child(userId); 

私は、リスナーの前に、このifステートメントを追加することで回避することができました。私はちょうどそれのように見えるようにしたくないです。どんな助けもありがとうございます。

+0

'user.getUid()'がnullであるとどう思いますか? –

+0

データベース参照にアクセスしようとするとこのエラーが発生するため、java.lang.NullPointerExceptionが発生します:child()の引数 'pathString'にnullを渡すことはできません------これは次に何を配置するのですかmDatabaseReference = FirebaseDatabase.getInstance ().getReference()。child( "bars")。子(userId)。 –

+0

'FirebaseDatabase.getInstance()。getReference()。child(" bars ")。child(userId)'を含むコードを投稿すると、コンテキストを見ることができます。 –

答えて

1

onAuthStateChanged()コールバックは非同期です。ユーザーがサインインするまで、isは有効なuserIDで起動しません。

声明:

mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("cars").child(userId); 

userId前に実行されているが、リスナーコールバックに値が割り当てられています。

+0

どうすればこの問題を解決するとお考えでしょうか? –

+0

あなたの全体的なUIの流れを知らなくても、本当に答えられることはありません。 auth UIの例として[Auth Quickstart Project](https://github.com/firebase/quickstart-android/tree/master/auth)を見てきましたか? –

+0

私は持っています。ありがとうございます –

関連する問題