我正在关注youtube上的一个教程,以制作火种的副本。我收到以下错误。有什么可能的解决方案?主要活动代码在android studio中未显示任何错误,但在运行时显示错误。
这是在android设备上测试应用程序时显示的错误。
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Object.equals(java.lang.Object)' on a null object reference
at com.techjd.hubu.MainActivity$6.onChildAdded(MainActivity.java:196)
at com.google.firebase.database.core.ChildEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.0:79)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.0:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.0:55)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5740)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)
这是主要活动。
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
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.lorentzos.flingswipe.SwipeFlingAdapterView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private cards cards_data[];
private ArrayAdapter arrayAdapter;
private int i;
private FirebaseAuth mAuth;
private String currentUId;
private DatabaseReference usersDb;
ListView listView;
List<cards> rowItems;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usersDb = FirebaseDatabase.getInstance().getReference().child("Users");
mAuth = FirebaseAuth.getInstance();
currentUId = mAuth.getCurrentUser().getUid();
checkUserSex();
rowItems = new ArrayList<cards>();
arrayAdapter = new arrayAdapter(this, R.layout.item, rowItems );
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
@Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
rowItems.remove(0);
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onLeftCardExit(Object dataObject) {
cards obj = (cards) dataObject;
String userId = obj.getUserId();
usersDb.child(oppositeUserSex).child(userId).child("connections").child("nope").child(currentUId).setValue(true);
Toast.makeText(MainActivity.this, "Left", Toast.LENGTH_SHORT).show();
}
@Override
public void onRightCardExit(Object dataObject) {
cards obj = (cards) dataObject;
String userId = obj.getUserId();
usersDb.child(oppositeUserSex).child(userId).child("connections").child("yes").child(currentUId).setValue(true);
isConnectionMatch(userId);
Toast.makeText(MainActivity.this, "Right", Toast.LENGTH_SHORT).show();
}
@Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
}
@Override
public void onScroll(float scrollProgressPercent) {
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
@Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this, "Item Clicked", Toast.LENGTH_SHORT).show();
}
});
}
private void isConnectionMatch(String userId) {
DatabaseReference currentUserConnectionsDB = usersDb.child(userSex).child(currentUId).child("connections").child("yes").child(userId);
currentUserConnectionsDB.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(MainActivity.this, "new Connection", Toast.LENGTH_LONG).show();
usersDb.child(oppositeUserSex).child(dataSnapshot.getKey()).child("connections").child("matches").child(currentUId).setValue(true);
usersDb.child(userSex).child(currentUId).child("connections").child("matches").child(dataSnapshot.getKey()).setValue(true);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private String userSex;
private String oppositeUserSex;
public void checkUserSex(){
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference maleDb = FirebaseDatabase.getInstance().getReference().child("Users").child("Male");
maleDb.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.getKey().equals(user.getUid())){
userSex = "Male";
oppositeUserSex = "Female";
getOppositeSexUsers();
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference femaleDb = FirebaseDatabase.getInstance().getReference().child("Users").child("Female");
femaleDb.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.getKey().equals(user.getUid())){
userSex = "Female";
oppositeUserSex = "Male";
getOppositeSexUsers();
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void getOppositeSexUsers(){
DatabaseReference oppositeSexDb = FirebaseDatabase.getInstance().getReference().child("Users").child(oppositeUserSex);
oppositeSexDb.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.exists() && !dataSnapshot.child("connections").child("nope").hasChild(currentUId) && !dataSnapshot.child("connections").child("yes").hasChild(currentUId)){
String profileImageUrl = "default";
if (!dataSnapshot.child("profileImageUrl").getValue().equals("default")){
profileImageUrl = dataSnapshot.child("profileImageUrl").getValue().toString();
}
cards item = new cards(dataSnapshot.getKey(), dataSnapshot.child("name").getValue().toString(), profileImageUrl);
rowItems.add(item);
arrayAdapter.notifyDataSetChanged();
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void logoutUser(View view) {
mAuth.signOut();
Intent intent = new Intent(MainActivity.this, ChooseLoginRegistrationActivity.class);
startActivity(intent);
finish();
return;
}
public void goToSettings(View view) {
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
intent.putExtra("userSex",userSex);
startActivity(intent);
return;
}
}
第196行是if(!dataSnapshot.child(“ profileImageUrl”)。getValue()。equals(“ default”))
答案 0 :(得分:0)
您的profileImageUrl的getValue
函数返回null。因此,当您在其上调用.equals
时,它不知道您的意思,因为该函数不存在于null上。
您可以简单地在调用.equals
之前先检查它是否为空。
Object profileImageUrlData = dataSnapshot.child("profileImageUrl").getValue();
if (profileImageUrlData != null && !profileImageUrlData.equals("default")){
profileImageUrl = profileImageUrlData.toString();
}
也许只是更改profileImageUrlData
的类型,所以它不是对象。我只是不确定会是什么。
答案 1 :(得分:0)
您在此行上得到一个NullPointerException
if (!dataSnapshot.child("profileImageUrl").getValue().equals("default")){
您的代码已到达该行,因此dataSnapshot不能为null,因为它已在上一行执行dataSnapshot.exists()
而没有任何错误。
此时您的代码获得NPE的唯一原因是dataSnapshot.child()为null,并且无法在null对象上调用.getValue()方法,或者.getValue()返回null。
比较字符串时,最好将静态字符串(如果有)放在比较的左侧。将您的代码更改为
if (dataSnapshot.child("profileImageUrl") != null &&
!"default".equals(dataSnapshot.child("profileImageUrl").getValue())){
上面的代码将首先检查dataSnapshot.child(“ profileImageUrl”)是否存在,然后将评估比较结果。您不必担心.getValue()是否为null,因为它在右侧是否正确,始终会在“默认”字符串上调用.equals。如果getValue()为null,则“ default” .equals(null)将返回false。