这是我的目录中显示的错误。它在HomeActivity的第89行显示错误,user.getName()为null。我是Android新手,因此无法修复此错误。
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android_foodbot, PID: 12641
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android_foodbot/com.example.android_foodbot.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.android_foodbot.AccountActivity.User.getName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.android_foodbot.AccountActivity.User.getName()' on a null object reference
at com.example.android_foodbot.HomeActivity.onCreate(HomeActivity.java:89)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
SignInActivity:
public class SignUpActivity extends AppCompatActivity {
private EditText inputName, inputPhone, inputEmail, inputPassword;
private FirebaseAuth auth;
private Button btnSignUp, btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
auth = FirebaseAuth.getInstance();
btnLogin = (Button) findViewById(R.id.btn_for_login);
btnSignUp = (Button) findViewById(R.id.btn_for_signUp);
inputName = (EditText) findViewById(R.id.name);
inputPhone = (EditText) findViewById(R.id.phone);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final ProgressDialog mDialog = new ProgressDialog(SignUpActivity.this);
mDialog.setMessage("Loading... Please wait!");
mDialog.show();
final String name = inputName.getText().toString().trim();
final String phone = inputPhone.getText().toString().trim();
final String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
if (TextUtils.isEmpty(name)) {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Enter your name!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(phone)) {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Enter your phone number!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(email)) {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
if (password.length() < 6) {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
return;
}
auth.createUserWithEmailAndPassword( email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
final User user = new User(
name,
email,
phone
);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
mDialog.dismiss();
if (task.isSuccessful()) {
mDialog.dismiss();
startActivity(new Intent(SignUpActivity.this, LoginActivity.class));
finish();
} else {
}
}
});
} else {
mDialog.dismiss();
Toast.makeText(SignUpActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
LoginActivity:
public class LoginActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private Button btnSignUp, btnLogin;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();
}
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btn_login);
btnSignUp = (Button) findViewById(R.id.btn_signUp);
auth = FirebaseAuth.getInstance();
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final ProgressDialog mDialog = new ProgressDialog(LoginActivity.this);
mDialog.setMessage("Loading... Please wait!");
mDialog.show();
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
mDialog.dismiss();
FirebaseDatabase database = FirebaseDatabase.getInstance();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance().getReference(uid).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.child("name").getValue(User.class);
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
Common.currentUser = user;
startActivity(intent);
finish();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
});
}
});
}
}
用户类具有三个参数以及它们的构造方法和获取方法设置方法:
public String name, email, phone;
Nav_header_home布局,必须在其中显示用户详细信息:
<TextView
android:id="@+id/textUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="@string/username"
android:textColor="#ffffff"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
家庭活动:
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference category;
FirebaseRecyclerAdapter<Category, MenuViewHolder> adapter;
TextView txtUserName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Menu");
setSupportActionBar(toolbar);
// Init Firebase
database = FirebaseDatabase.getInstance();
category = database.getReference("Category");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent cartIntent = new Intent(HomeActivity.this, CartActivity.class);
startActivity(cartIntent);
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FirebaseDatabase database = FirebaseDatabase.getInstance();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance().getReference().child("User").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Common.currentUser = dataSnapshot.getValue(User.class);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
// Set Name for User
View headerView = navigationView.getHeaderView(0);
txtUserName = (TextView)findViewById(R.id.textUserName);
txtUserName.setText(Common.currentUser.getName());
// Loading menu
recycler_menu = findViewById(R.id.recycler_menu);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
recycler_menu.setLayoutManager(layoutManager);
recycler_menu.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
}
/**
* RecyclerView item decoration - give equal margin around grid item
*/
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
/**
* Converting dp to pixel
*/
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.logout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(this, LoginActivity.class));
break;
}
return true;
// return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_menu) {
// Handle the camera action
} else if (id == R.id.nav_orders) {
} else if (id == R.id.nav_cart) {
} else if (id == R.id.nav_logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
protected void onResume() {
super.onResume();
// loadMenu();
adapter = new FirebaseRecyclerAdapter<Category, MenuViewHolder>(Category.class,
R.layout.menu_item,
MenuViewHolder.class,
category) {
@Override
protected void populateViewHolder(MenuViewHolder viewHolder, Category model, int position) {
viewHolder.txtMenuName1.setText(model.getName1());
// viewHolder.txtMenuPrice1.setText(model.getPrice1());
Picasso.with(getBaseContext()).load(model.getImage1())
.into(viewHolder.imageView1);
final Category clickItem = model;
viewHolder.setItemClickListener(new ItemClickListener() {
@Override
public void onClick(View view, int position, boolean isLongClick) {
//
// Get Category id and Start new activity
Intent foodList = new Intent(HomeActivity.this,
FoodListActivity.class);
foodList.putExtra("CategoryId", adapter.getRef(position).getKey());
startActivity(foodList);
}
});
}
};
recycler_menu.setAdapter(adapter);
}
}
答案 0 :(得分:0)
我想问题出在这里。 用户user = dataSnapshot.child(“ name”)。getValue(User.class);
情况1:如果仅需要用户名,则应为: 字符串名称= dataSnapshot.child(“名称”).getValue(String.class);
情况2:如果您需要整个用户对象,则应为: 用户用户= dataSnapshot.getValue(User.class);
因为您的引用指向一个字符串对象,而不是一个用户对象。
根据您的代码(Common.currentUser =用户),您可能需要直接使用用户对象。(案例2)
答案 1 :(得分:0)
通过登录活动之类的
更新代码User user = dataSnapshot.getValue(User.class);
,您也不会得到child("Users")
。因此,请像这样更新代码
FirebaseDatabase database = FirebaseDatabase.getInstance();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance().getReference("Users").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
Common.currentUser = user;
startActivity(intent);
finish();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
在家庭活动中,您给 child(“ User”),但是您需要给 child(“ Users”) >
希望能对您有所帮助!
谢谢。
答案 2 :(得分:-1)
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance().getReference(uid).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.child("name").getValue(User.class);
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
Common.currentUser = user;
startActivity(intent);
finish();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
如果以此替换该部件,则很可能会解决您的问题。如果没有,也许您需要以json格式(至少Users /)共享数据库
// You should check if uid == null?
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance().getReference().child("Users").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
Common.currentUser = user;
startActivity(intent);
finish();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});