0

I am following one tutorial from youtube for making a clone of tinder. I am getting the following error. What can be the possible solution? The code of main activity doesn't show any error in the android studio but on running it shows an error.

This is the error it is showing on testing the app on android device .

 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)

This is the main activity.

  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;
}

}

Line 196 is if (!dataSnapshot.child("profileImageUrl").getValue().equals("default"))

Tech jd
  • 23
  • 2
  • 7
  • possible duplicate : https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it. here dataSnapshot.child("profileImageUrl").getValue() is null ! – SebastienRieu Oct 31 '19 at 13:26
  • At which line of code are you getting that error? Please also responde with @AlexMamo – Alex Mamo Oct 31 '19 at 13:26
  • According log `dataSnapshot.child("profileImageUrl").getValue()` return null. Check first whether it's null or not and then compare with `default` – Md. Asaduzzaman Oct 31 '19 at 13:29
  • dataSnapshot.child("default") is null. That is the problem. When you comparing known Strings with a dynamic String (variable) you should do "String".equals(StringVariable) – Ioannis Barakos Oct 31 '19 at 13:31

2 Answers2

0

Your getValue function for profileImageUrl is returning null. So when you call .equals on it, it doesn't know what you mean because the function doesn't exist on null.

You could simply check if it is null first before you call .equals.

Object profileImageUrlData = dataSnapshot.child("profileImageUrl").getValue();

if (profileImageUrlData != null && !profileImageUrlData.equals("default")){
    profileImageUrl = profileImageUrlData.toString();
}

Maybe just change the type of profileImageUrlData so it isn't Object. I just wasn't sure what it would be.

0

You get a NullPointerException on this line

 if (!dataSnapshot.child("profileImageUrl").getValue().equals("default")){

Your code has reached that line, therefore dataSnapshot cannot be null as it has already executed dataSnapshot.exists() on the previous line without any error.

The only reason your code gets a NPE at that point is that the dataSnapshot.child() is null and the .getValue() method cannot be invoked on a null object or the .getValue() returns null.

When comparing Strings, its better to have the static String (if any) on the left side of the comparison. Change your code to

 if (dataSnapshot.child("profileImageUrl") != null &&
 !"default".equals(dataSnapshot.child("profileImageUrl").getValue())){

The above code will first check if dataSnapshot.child("profileImageUrl") exists and then will evaluate the comparison. You do not care if .getValue() is null as it is on the right side, the .equals will always be called on the "default" String. If getValue() is null, the "default".equals(null) will return false.

Ioannis Barakos
  • 1,319
  • 1
  • 11
  • 16