我是android应用程序开发的新手。我一直在尝试使用Firebase电子邮件和密码身份验证来构建应用,还试图在注册过程中将手机的ANDROID_ID
保存在Firebase数据库中。
但是,每当我打开SignUp活动时,该应用程序都会关闭并在Logcat中显示以下错误:
java.lang.RuntimeException:无法实例化活动 ComponentInfo {com.rimikri.smartpedi / com.rimikri.smartpedi.SignUpActivity}: java.lang.NullPointerException:尝试调用虚拟方法 'android.content.ContentResolver 空对象上的android.content.Context.getContentResolver()' 参考
这是我的注册活动:
public class SignUpActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextName;
private FirebaseAuth mAuth;
public String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
editTextName = findViewById(R.id.edit_text_name);
mAuth = FirebaseAuth.getInstance();
}
private void registerUser() {
final String name = editTextName.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener < AuthResult > () {
@Override
public void onComplete(@NonNull Task < AuthResult > task) {
if (task.isSuccessful()) {
User user = new User(
name,
androidId
);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener < Void > () {
@Override
public void onComplete(@NonNull Task < Void > task) {
//
}
});
} else {
//
}
}
});
}
}
我上的课程User
是:
public class User {
public String name;
public User() {
}
public User(String name) {
this.name = name;
}
}
如何在这里获取ANDROID_ID?
答案 0 :(得分:0)
将您的androidId
放入 onCreate()
方法
尝试一下
public class SignUpActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextName;
private FirebaseAuth mAuth;
public String androidId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
editTextName = findViewById(R.id.edit_text_name);
mAuth = FirebaseAuth.getInstance();
androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
}
private void registerUser() {
final String name = editTextName.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener < AuthResult > () {
@Override
public void onComplete(@NonNull Task < AuthResult > task) {
if (task.isSuccessful()) {
User user = new User(
name,
androidId
);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener < Void > () {
@Override
public void onComplete(@NonNull Task < Void > task) {
//
}
});
} else {
//
}
}
});
}
}