我正在从事我的Android Studio项目。我想做的是转到该成员的ID,然后获取其名称。我将附加Firebase数据库图片。
我不确定该怎么办。我要登录,然后转到MenuActivity.java。当我登录时,转到MenuActivity.java时崩溃。我想从数据库中获取名称的原因是因为在MenuActivity.java的顶部,我希望它说“你好,名称!”。因此,我需要登录个人的姓名。
我检查了所有内容。一切似乎令人困惑,我目前遇到此错误。
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.cis436.ewalletprototype, PID: 10053
java.lang.NullPointerException: **Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()'** on a null object reference
at com.cis436.ewalletprototype.MenuActivity$1.onDataChange(MenuActivity.java:66)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@18.0.1:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@18.0.1:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@18.0.1:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I/Process: Sending signal. PID: 10053 SIG: 9
Application terminated.
这是signInActivity.java
package com.cis436.ewalletprototype;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
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;
public class signInActivity extends AppCompatActivity {
int RC_SIGN_IN = 0;
Button btnSignIn;
Button btnSignUp;
Button btnSignInGoogle;
Button btnSignInFacebook;
EditText txtEmailInput;
EditText txtPasswordInput;
TextView btnForgotPassword;
private FirebaseAuth mAuth;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
btnSignIn = findViewById(R.id.btnSignIn);
btnSignUp = findViewById(R.id.sign_up);
btnSignInGoogle = findViewById(R.id.sign_in_google);
btnSignInFacebook = findViewById(R.id.sign_in_facebook);
txtEmailInput = findViewById(R.id.txtEmail);
txtPasswordInput = findViewById(R.id.txtPassword);
btnForgotPassword = findViewById(R.id.txtForgotPassword);
mAuth = FirebaseAuth.getInstance();
//if (mAuth.getCurrentUser() != null) {
// startActivity(new Intent(signInActivity.this, MenuActivity.class));
// finish();
//}
btnSignUp.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(signInActivity.this, signUpActivity.class));
}
});
//Click Listeners for buttons
btnSignIn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent signUpP2 = new Intent(signInActivity.this,MenuActivity.class);
finish();
startActivity(signUpP2);
}
});
btnSignIn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = txtEmailInput.getText().toString();
final String password = txtPasswordInput.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
//authenticate user
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(signInActivity.this,
new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful())
{
// there was an error
if (password.length() < 6)
{
Toast.makeText(signInActivity.this, "Password must be at least 6 characters", Toast.LENGTH_SHORT).show();
txtPasswordInput.setError(getString(R.string.minimum_password));
}
else
{
Toast.makeText(signInActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
}
else
{
if(mAuth.getCurrentUser().isEmailVerified())
{
Toast.makeText(signInActivity.this, "Registered successfully. Please check your email for verification", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(signInActivity.this, MenuActivity.class);
startActivity(intent);
finish();
}
}
}
});
}
});
}
}
这是MenuActivity.java
package com.cis436.ewalletprototype;
import android.app.Activity;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
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 com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;
import java.util.ArrayList;
public class MenuActivity extends Activity {
private static final String TAG = "ViewDatabase";
private DrawerLayout drawer;
private TextView txtWelcomeName;
String mName,mID;
Member member;
long maxid = 0;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private String userID;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
txtWelcomeName = findViewById(R.id.tb_welcomeMessage);
//declare the database reference object. This is what we use to access the database.
//NOTE: Unless you are signed in, this will not be useable.
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
myRef = FirebaseDatabase.getInstance().getReference().child("Member").child(userID);
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
txtWelcomeName.setText(name);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
//Bottom Navigation
BottomNavigationViewEx bottomNavigationViewEx = findViewById(R.id.bottom_bar);
bottomNavigationViewEx.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.hamburgerAction:
drawer.openDrawer(GravityCompat.START);
break;
case R.id.reportAction:
Intent report = new Intent(MenuActivity.this, ContactActivity.class);
startActivity(report);
break;
case R.id.notificationsAction:
Intent notifications = new Intent(MenuActivity.this, NotificationsActivity.class);
startActivity(notifications);
break;
case R.id.settingsAction:
Intent settings = new Intent(MenuActivity.this, SettingsActivity.class);
startActivity(settings);
break;
}
return true;
}
});
//Drawer Navigation
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch(menuItem.getItemId()) {
case R.id.dm_profile:
Intent profile = new Intent(MenuActivity.this, ProfileActivity.class);
drawer.closeDrawer(GravityCompat.START);
startActivity(profile);
break;
case R.id.dm_settings:
Intent settings = new Intent(MenuActivity.this, ContactActivity.class);
drawer.closeDrawer(GravityCompat.START);
startActivity(settings);
break;
case R.id.dm_help:
Intent help = new Intent(MenuActivity.this, HelpActivity.class);
drawer.closeDrawer(GravityCompat.START);
startActivity(help);
break;
case R.id.dm_logout:
//Logout of account
break;
}
return true;
}
});
//Main Menu Buttons
Button btnMakePayment = findViewById(R.id.btnMakePayment);
Button btnSendMoney = findViewById(R.id.btnSendMoney);
Button btnContact = findViewById(R.id.btnReport);
Button btnSettings = findViewById(R.id.btnSettings);
Button btnCalendar = findViewById(R.id.btnCalendar);
btnMakePayment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent makePayment = new Intent(MenuActivity.this, MakePaymentActivity.class);
startActivity(makePayment);
}
});
btnContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent contact = new Intent(MenuActivity.this, ContactActivity.class);
startActivity(contact);
}
});
btnSettings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent settings = new Intent(MenuActivity.this, SettingsActivity.class);
startActivity(settings);
}
});
btnCalendar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent calendar = new Intent(MenuActivity.this, CalendarActivity.class);
startActivity(calendar);
}
});
/////////////////////////////////////////////////////////////////////////////////////////////////////////
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMessage("Successfully signed in with: " + user.getEmail());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
toastMessage("Successfully signed out.");
}
// ...
}
};
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
showData(dataSnapshot);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
txtWelcomeName.setText(mName);
}
////////////////////////////////
/////////////////////////////////////
private void showData(DataSnapshot dataSnapshot) {
Member member = dataSnapshot.getValue(Member.class);
mName = member.getName();
txtWelcomeName.setText(mName);
//display all the information
//Log.d(TAG, "showData: name: " + member.getName());
//txtWelcomeName.setText(member.getName());
ArrayList<String> array = new ArrayList<>();
array.add(member.getName());
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}
@Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
这是我的Member.class
package com.cis436.ewalletprototype;
public class Member {
private String name="";
private String email="";
private String date="";
private String homeAddress="";
private String country="";
private String companyName="";
private String companyAddress="";
private String zipcode="";
private String memberId="";
private String paypalEmail="";
public Member()
{
}
public Member(String memberId, String email, String date, String homeAddress, String country, String companyName, String companyAddress, String zipcode, String paypalEmail, String name)
{
this.memberId = memberId;
this.email = email;
this.name = name;
this.date = date;
this.homeAddress = homeAddress;
this.country = country;
this.companyName = companyName;
this.companyAddress = companyAddress;
this.zipcode = zipcode;
this.paypalEmail = paypalEmail;
}
public String getMemberId() { return memberId; }
public void setMemberId(String memberId) { this.memberId = memberId; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getDate() { return date; }
public void setDate(String date) { this.date = date; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getHomeAddress() { return homeAddress; }
public void setHomeAddress(String homeAddress) { this.homeAddress = homeAddress; }
public String getCountry() { return country; }
public void setCountry(String country) { this.email = country; }
public String getCompanyName() { return companyName; }
public void setCompanyName(String companyName) { this.companyName = companyName; }
public String getCompanyAddress() { return companyAddress; }
public void setCompanyAddress(String companyAddress) { this.companyAddress = companyAddress; }
public String getZipcode() { return zipcode; }
public void setZipcode(String zipcode) { this.zipcode = zipcode; }
public String getPaypalEmail() { return paypalEmail; }
public void setPaypalEmail(String paypalEmail) { this.paypalEmail = paypalEmail; }
}
这是我当前数据库的图片:
答案 0 :(得分:1)
使用以下代码行时:
FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
getUid()
方法将返回经过身份验证的用户的ID。将userID
传递到以下行时:
myRef = FirebaseDatabase.getInstance().getReference().child("Member").child(userID);
这意味着您正在设置对具有密钥uid
的用户对象的引用,该对象来自身份验证过程。正如我在您的数据库中看到的那样,用户的密钥不是上面的一个,它是由push()
方法生成的随机密钥,请参见以-
(减号)开头的
要解决此问题,您可以使用实际的用户ID更改该按键,这是推荐的解决方案,这还意味着您需要再次将用户对象添加到数据库中,或者可以使用以下查询:>
Query query = myRef = FirebaseDatabase.getInstance().getReference()
.child("Member")
.orderByChild("memberId")
.equalTo("-LlGrtcsbW6jLWKoLhLw");
其他一切都可以正常工作。
答案 1 :(得分:0)
您可以在下面尝试。
myRef = FirebaseDatabase.getInstance().getReference().child("Member").child(userID);
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Member member = dataSnapshot.getValue(Member.class);
String name = member.getName();
txtWelcomeName.setText(name);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
答案 2 :(得分:0)
使用getvalue()函数时,必须传递要检索其值的对象的类名。请尝试以下操作。
代替:
String name = dataSnapshot.child("name").getValue().toString();
您必须使用:
String name = dataSnapshot.child("name").getValue(String.class);
您可以阅读Firebase文档以获取更多信息。 https://firebase.google.com/docs/database/android/read-and-write