【发布时间】:2020-01-28 03:19:53
【问题描述】:
所以我正在开发一个聊天应用程序,并且我一直在 Android 模拟器中对其进行测试(像素 3 选项)。但是现在我正试图让它在另一个模拟器中运行(这次我选择了一个像素 2)并且没有运行。
我会传递一些代码,包括 MainActivity。
这是来自 LogCat
2020-01-28 01:47:27.799 10456-10456/com.example.textmefinal E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.textmefinal, PID: 10456
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.textmefinal/com.example.textmefinal.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.example.textmefinal.MainActivity.onCreate(MainActivity.java:44)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2020-01-28 01:47:57.456 10456-10494/com.example.textmefinal E/FirebaseInstanceId:令牌检索失败:SERVICE_NOT_AVAILABLE
主要活动
package com.example.textmefinal;
公共类 MainActivity 扩展 AppCompatActivity {
private Toolbar mToolbar;
private ViewPager myViewPager;
private TabLayout myTabLayout;
private TabsAccessorAdapter myTabsAccessorAdapter;
private FirebaseUser currentUser;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private String currentUserID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
currentUserID = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("TextMe");
myViewPager = (ViewPager) findViewById(R.id.main_tabs_pager);
myTabsAccessorAdapter = new TabsAccessorAdapter(getSupportFragmentManager());
myViewPager.setAdapter(myTabsAccessorAdapter);
myTabLayout = (TabLayout) findViewById(R.id.main_tabs);
myTabLayout.setupWithViewPager(myViewPager);
}
@Override
protected void onStart() {
super.onStart();
if (currentUser == null){
SendUserToLoginActivity();
}
else {
VerifyUserExistance();
}
}
private void VerifyUserExistance() {
String currentUserId = mAuth.getCurrentUser().getUid();
RootRef.child("Users").child(currentUserId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if ((dataSnapshot.child("name").exists())){
Toast.makeText(MainActivity.this, "Welcome", Toast.LENGTH_SHORT).show();
}
else {
SendUserToSettingsActivity();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.main_logout_option){
mAuth.signOut();
SendUserToLoginActivity();
}
if (item.getItemId() == R.id.main_settings_option){
SendUserToSettingsActivity();
}
if (item.getItemId() == R.id.main_find_friends_option){
SendUserToFindFriendsActivity();
}
return true;
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
//finish();
}
private void SendUserToSettingsActivity() {
Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(settingsIntent);
}
private void SendUserToFindFriendsActivity() {
Intent findFriendsIntent = new Intent(MainActivity.this, FindFriendsActivity.class);
startActivity(findFriendsIntent);
}
}
登录活动
package com.example.textmefinal;
公共类 LoginActivity 扩展 AppCompatActivity {
private FirebaseAuth mAuth;
private ProgressDialog loadingBar;
private Button LoginButton, PhoneLoginButton;
private EditText UserEmail, UserPassword;
private TextView NeedNewAccountLink, ForgetPasswordLink;
private DatabaseReference UsersRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
InitializeFields();
NeedNewAccountLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SendUserToRegisterActivity();
}
});
LoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AllowUserToLogin();
}
});
}
@Override
protected void onStart()
{
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null)
{
SendUserToMainActivity();
}
}
private void AllowUserToLogin() {
String email = UserEmail.getText().toString();
String password = UserPassword.getText().toString();
if (TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter email...", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter password...", Toast.LENGTH_SHORT).show();
}
else {
loadingBar.setTitle("Sign In");
loadingBar.setMessage("Please wait...");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
String currentUserId = mAuth.getCurrentUser().getUid();
String deviceToken = FirebaseInstanceId.getInstance().getToken();
UsersRef.child(currentUserId).child("device_token")
.setValue(deviceToken)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(LoginActivity.this, "Logged in Successful", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else {
String message = task.getException().toString();
Toast.makeText(LoginActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void InitializeFields() {
LoginButton = (Button) findViewById(R.id.login_button);
PhoneLoginButton = (Button) findViewById(R.id.phone_login_button);
UserEmail = (EditText) findViewById(R.id.login_email);
UserPassword = (EditText) findViewById(R.id.login_password);
NeedNewAccountLink = (TextView) findViewById(R.id.need_new_account_link);
ForgetPasswordLink = (TextView) findViewById(R.id.forget_password_link);
loadingBar = new ProgressDialog(this);
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(LoginActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
private void SendUserToRegisterActivity() {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(registerIntent);
}
}
注册活动
package com.example.textmefinal;
公共类 RegisterActivity 扩展 AppCompatActivity {
private Button CreateAccountButton;
private EditText UserEmail, UserPassword;
private TextView AlreadyHaveAccountLink;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private ProgressDialog loadingBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mAuth = FirebaseAuth.getInstance();
RootRef = FirebaseDatabase.getInstance().getReference();
InitializeFields();
AlreadyHaveAccountLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SendUserToLoginActivity();
}
});
CreateAccountButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CreateNewAccount();
}
});
}
private void CreateNewAccount() {
String email = UserEmail.getText().toString();
String password = UserPassword.getText().toString();
if (TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter email...", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter password...", Toast.LENGTH_SHORT).show();
}
else {
loadingBar.setTitle("Creating New Account");
loadingBar.setMessage("Please wait, while we are creating new account for you...");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
String deviceToken = FirebaseInstanceId.getInstance().getToken();
String currentUserID = mAuth.getCurrentUser().getUid();
RootRef.child("Users").child(currentUserID).setValue("");
RootRef.child("Users").child(currentUserID).child("device_token")
.setValue(deviceToken);
SendUserToMainActivity();
Toast.makeText(RegisterActivity.this, "Account Created Successfully...", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else {
String message = task.getException().toString();
Toast.makeText(RegisterActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void InitializeFields() {
CreateAccountButton = (Button) findViewById(R.id.register_button);
UserEmail = (EditText) findViewById(R.id.register_email);
UserPassword = (EditText) findViewById(R.id.register_password);
AlreadyHaveAccountLink = (TextView) findViewById(R.id.already_have_account_link);
loadingBar = new ProgressDialog(this);
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(loginIntent);
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(RegisterActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
谁能帮助我?
【问题讨论】:
-
分享 logcat 消息。
标签: android android-studio android-emulator