在Firebase中获取“java.lang.NullPointerException:无法为child()中的参数'pathString'传递null”

时间:2018-03-11 20:30:01

标签: java android firebase firebase-realtime-database

Image of DB in firebase console

我真的不知道这里有什么问题,我可以在其他活动上添加数据。我收到错误“java.lang.NullPointerException:无法为child()中的参数'pathString'传递null”,并且不知道如何修复。还有另外3个类只创建另一个类,即向firebase实时数据库存储添加数据。

package com.example.akshay.katiroll.FirstScreen;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.akshay.katiroll.R;
import com.example.akshay.katiroll.SecondScreen.welcome;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class Profile extends AppCompatActivity {

    EditText fName, lName, PhNo, BDay, Zip;
    Button svBtn;
    DatabaseReference mDataReference;
    String keyUser;
    String fNameStr, lNameStr, PhNoStr, BDayStr, ZipStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        keyUser = getIntent().getStringExtra("USER_KEY");
        mDataReference = FirebaseDatabase.getInstance().getReference().child("Users").child(keyUser);//error in this line
        fName = (EditText) findViewById(R.id.fName); 
        lName = (EditText) findViewById(R.id.lName);
        PhNo = (EditText) findViewById(R.id.phno);
        BDay = (EditText) findViewById(R.id.bday);
        Zip = (EditText) findViewById(R.id.zip);
        svBtn = (Button) findViewById(R.id.svBtn);
        svBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                fNameStr = fName.getText().toString();
                lNameStr = lName.getText().toString();
                PhNoStr = PhNo.getText().toString();
                BDayStr = BDay.getText().toString();
                ZipStr = Zip.getText().toString();

                if(!TextUtils.isEmpty(fNameStr) && !TextUtils.isEmpty(lNameStr) && !TextUtils.isEmpty(PhNoStr)) {
                    DatabaseReference mDataRef = mDataReference.child("Users").push();
                    mDataRef.child("firstName").setValue(""+fNameStr);
                    mDataRef.child("lastName").setValue(""+lNameStr);
                    mDataRef.child("phoneNumber").setValue(""+PhNoStr);
                    mDataRef.child("isVerified").setValue("verified");
                    if(!TextUtils.isEmpty(BDayStr)){
                        mDataRef.child("birthday").setValue(""+BDayStr);
                    }else{ 
                        mDataRef.child("birthday").setValue("null");
                    }
                    if(!TextUtils.isEmpty(ZipStr)){
                        mDataRef.child("zipcode").setValue("ZipStr");
                    }else{
                        mDataRef.child("zipcode").setValue("null");
                    }
                    Toast.makeText(Profile.this, "User profile added", Toast.LENGTH_LONG).show();

                    startActivity(new Intent(Profile.this, welcome.class));

                }else{
                    Toast.makeText(Profile.this, "Failed to create User Account", Toast.LENGTH_LONG).show();

                }
            }
        });
    }
}





package com.example.akshay.katiroll.FirstScreen;

import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import com.example.akshay.katiroll.R;
import com.example.akshay.katiroll.SecondScreen.welcome;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.Iterator;


public class katiRoll extends AppCompatActivity {
    EditText userEdit;
    EditText passEdit;
    String sUser, sPass;
    Button sign;
    Button reg;
    Boolean signInVLogIn;
    FirebaseAuth mAuth;
    FirebaseAuth.AuthStateListener mAuthListener;
    DatabaseReference mDatabaseRef;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kati_roll);
        float Re = 255;
        float Gr = 148;
        float Bl = 0;
        userEdit = (EditText)findViewById(R.id.user);
        passEdit = (EditText)findViewById(R.id.pass);
        sign = (Button) findViewById(R.id.sign);
        reg = (Button) findViewById(R.id.reg);
        userEdit.setTextColor(Color.rgb(Re,Gr,Bl));
        passEdit.setTextColor(Color.rgb(Re,Gr,Bl));
        sign.setTextColor(Color.rgb(Re,Gr,Bl));
        reg.setTextColor(Color.rgb(Re,Gr,Bl));
        mAuth = FirebaseAuth.getInstance();
        mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("Users");
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if(!TextUtils.isEmpty(sUser) && !TextUtils.isEmpty(sPass)){
                    signInVLogIn = true;
                }else{
                    signInVLogIn = false;
                }
                if(user != null && signInVLogIn) {

                }else{
                    //Toast.makeText(katiRoll.this, "Log In Failed", Toast.LENGTH_LONG).show();
                }
            }
        };
        sign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sUser = userEdit.getText().toString().trim();
                sPass = passEdit.getText().toString().trim();

                if(!TextUtils.isEmpty(sUser) && !TextUtils.isEmpty(sPass))
                {

                    mAuth.signInWithEmailAndPassword(sUser, sPass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if(task.isSuccessful()){
                                mDatabaseRef.addValueEventListener(new ValueEventListener() {
                                    @Override
                                    public void onDataChange(DataSnapshot dataSnapshot) {


                                        checkUserValidation(dataSnapshot, sUser);

                                    }

                                    @Override
                                    public void onCancelled(DatabaseError databaseError) {

                                    }
                                });
                            }else{
                                Toast.makeText(katiRoll.this, "User Login Doesn't Exist" , Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
            }
        });
        reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(katiRoll.this, signUp.class));
            }
        });

    }

    private void checkUserValidation(DataSnapshot dataSnapshot, String emailForVer) {
               Iterator iterator = dataSnapshot.getChildren().iterator();

        while (iterator.hasNext())
        {

            DataSnapshot dataUser = (DataSnapshot)iterator.next();

            if (dataUser.child("emailUser").getValue().toString().equals(emailForVer)){
                if(dataUser.child("isVerified").getValue().toString().equals("unverified"))
                {
                    Intent in = new Intent(katiRoll.this, Profile.class);
                    in.putExtra("USER KEY", dataUser.child("userKey").getValue().toString());
                    startActivity(in);
                    Log.d("USERKEY",dataUser.child("userKey").getValue().toString());
                }
                else{
                    startActivity(new Intent(katiRoll.this, welcome.class));
                }
            }

        }



    }

    @Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(mAuthListener !=null){
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

}

package com.example.akshay.katiroll.FirstScreen;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.akshay.katiroll.SecondScreen.welcome;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import com.example.akshay.katiroll.R;
import com.google.firebase.database.ValueEventListener;

import java.util.Iterator;

public class signUp extends AppCompatActivity {

    EditText nUser, nPass;
    Button registerBtn, backToMain;
    ImageButton passVis;
    FirebaseAuth mAuth;
    FirebaseAuth.AuthStateListener mAuthListener;
    DatabaseReference mDatabaseRef, mUserCheckData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        nUser = (EditText) findViewById(R.id.nUser);
        nPass = (EditText) findViewById(R.id.nPass);
        registerBtn = (Button) findViewById(R.id.registerBtn);
        backToMain = (Button) findViewById(R.id.backToMain);
        passVis = (ImageButton)findViewById(R.id.passVis);
        passVis.setImageResource(R.drawable.open);
        passVis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Drawable drawable = passVis.getDrawable();
                if(drawable.getConstantState().equals(getResources().getDrawable(R.drawable.open,null).getConstantState())){
                    passVis.setImageResource(R.drawable.closed);
                    nPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

                }else{
                    passVis.setImageResource(R.drawable.open);
                    nPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD);
                }
            }
        });
        float Re = 255;
        float Gr = 148;
        float Bl = 0;
        nUser.setTextColor(Color.rgb(Re, Gr, Bl));
        nPass.setTextColor(Color.rgb(Re, Gr, Bl));
        registerBtn.setTextColor(Color.rgb(Re, Gr, Bl));
        backToMain.setTextColor(Color.rgb(Re, Gr, Bl));
        mAuth = FirebaseAuth.getInstance();
        mDatabaseRef = FirebaseDatabase.getInstance().getReference();
        mUserCheckData = FirebaseDatabase.getInstance().getReference().child("User");
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    final String emailForVer = user.getEmail();
                    mUserCheckData.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            checkForValidation(dataSnapshot, emailForVer);
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });
                } else {
                    Log.d("TAG", "onAuthStateChanged:signed_out");
                }

            }
        };
        registerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String nUserString, nPassString;
                nUserString = (nUser.getText().toString().trim());
                nPassString = (nPass.getText().toString().trim());
                if(nPassString.length()>=6){
                    if (!TextUtils.isEmpty(nUserString) && !TextUtils.isEmpty(nPassString)) {

                        mAuth.createUserWithEmailAndPassword(nUserString, nPassString).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {

                                if (task.isSuccessful()) {
                                    DatabaseReference mChildDatabase = mDatabaseRef.child("Users").push();
                                    String key_user = mChildDatabase.getKey();
                                    mChildDatabase.child("isVerified").setValue("unverified");
                                    mChildDatabase.child("userKey").setValue(key_user);
                                    mChildDatabase.child("EmailUser").setValue(nUserString);
                                    mChildDatabase.child("PasswordUser").setValue(nPassString);
                                    Toast.makeText(signUp.this, "User Account Created, Check Email For Confirmation", Toast.LENGTH_LONG).show();

                                    FirebaseUser user = mAuth.getCurrentUser();
                                    if (user != null) {
                                        user.sendEmailVerification();
                                    }

                                    startActivity(new Intent(signUp.this, Profile.class));

                                } else {
                                    Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
                                }
                            }
                        });
                    } else {
                        Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
                    }

                }else {
                    Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
                }
            }
        });
        backToMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(signUp.this, katiRoll.class));
            }
        });


    }

    private void checkForValidation(DataSnapshot dataSnapshot, String emailForVer) {
        Iterator iterator = dataSnapshot.getChildren().iterator();

        while (iterator.hasNext())
        {

            DataSnapshot dataUser = (DataSnapshot)iterator.next();

            if (dataUser.child("emailUser").getValue().toString().equals(emailForVer)){
                if(dataUser.child("isVerified").getValue().toString().equals("unverified"))
                {
                    Intent in = new Intent(signUp.this, Profile.class);
                    in.putExtra("USER KEY", dataUser.child("userKey").getValue().toString());
                    startActivity(in);
                    Log.d("USERKEY",dataUser.child("userKey").getValue().toString());

                }
                else{
                    startActivity(new Intent(signUp.this, welcome.class));
                }
            }

        }



    }

    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(mAuthListener !=null){
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }
}

package com.example.akshay.katiroll.SecondScreen;

import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.example.akshay.katiroll.FirstScreen.katiRoll;
import com.example.akshay.katiroll.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class welcome extends AppCompatActivity {
    Button logOutBtn;
    FirebaseAuth mAuth;
    FirebaseAuth.AuthStateListener mAuthListener;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        float Re = 255;
        float Gr = 148;
        float Bl = 0;
        logOutBtn = (Button)findViewById(R.id.logOutBtn);
        logOutBtn.setTextColor(Color.rgb(Re,Gr,Bl));
        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if(user !=null) {


                }else{



                }
            }
        };
        logOutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAuth.signOut();
                finish();
                startActivity(new Intent(welcome.this, katiRoll.class));
            }
        });
    }
    @Override
    protected void onStart() {
        super.onStart();

        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    protected void onStop() {
        super.onStop();

        mAuth.removeAuthStateListener(mAuthListener);
    }
}

1 个答案:

答案 0 :(得分:1)

告诉你的问题是你做错了参考,你试图让Firebase Database里面的东西不存在

此行告诉您当前数据库结构中不存在child("Users").child(KeyUser);

要解决此问题,您应该看到数据库结构,然后重做您的参考。

如果您发布Firebase数据库的照片,我很乐意根据您的需要重构您的代码。

此处您的错误USER_KEY

keyUser = getIntent().getStringExtra("USER_KEY");

解决这个问题的方法很简单,就是这样做

 keyUser = getIntent().getExtras().getString("USER_KEY");

你是从哪里获得意图的?如果你想从另一个Activity获取一个putExtra,你做错了,发布你正在设置额外的("USER_KEY");

如果没有其他内容,

Intent.getStringExtra()Intent.getExtras()将返回null,因此您需要在尝试调用getString()之前检查该内容

首先检查附加内容的一个简单示例是

String keyUser;
Bundle extras = getIntent().getExtras();
if(extras == null) {
    Log.e("keyUser is null","");
} else {
    keyUser= extras.getString("USER_KEY");
}

快乐编码