-1

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 'java.lang.String java.lang.Object.toString()' on a null object reference
    at com.techjd.hubu.MainActivity$6.onChildAdded(MainActivity.java:201)
    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";
                Object profileImageUrlData = dataSnapshot.child("profileImageUrl").getValue();

                if (profileImageUrlData != null && !profileImageUrlData.equals("default")){
                    profileImageUrl = profileImageUrlData.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 201 is cards item = new cards(dataSnapshot.getKey(), dataSnapshot.child("name").getValue().toString(), profileImageUrl);

Tech jd
  • 1
  • 2
  • 4
  • @azurefrog But how do I solve it here? – Tech jd Oct 31 '19 at 18:14
  • 2
    This sounds like a great opportunity for you to spend some time learning [how to debug](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) your code. – azurefrog Oct 31 '19 at 18:17
  • @azurefrog I tried but it is constantly showing Null Pointer Exception. Can you please tell me solution? Thanks in Advance! – Tech jd Oct 31 '19 at 18:33

1 Answers1

0

Check first whether it is null or not and then try to get String from it.

Object nameData = dataSnapshot.child("name").getValue();
String nameDefault = "default";

if (nameData != null){
    nameDefault = nameData.toString();
}

Then use

cards item = new cards(nameDefault, profileImageUrl);
Md. Asaduzzaman
  • 14,081
  • 2
  • 26
  • 39
  • It's still showing the same error. – Tech jd Oct 31 '19 at 18:58
  • Now which line? – Md. Asaduzzaman Oct 31 '19 at 19:00
  • Still, it is showing on the same line. – Tech jd Oct 31 '19 at 19:02
  • `nameData != null`, Did you use that? I have check the null. `nameDefault = nameData.toString();` this line should not be executed. Then how can you get this line? Please update your code with my answer – Md. Asaduzzaman Oct 31 '19 at 19:04
  • `Object ImageData = dataSnapshot.child("profileImageUrl").getValue(); String ImageDefault = "default"; if (ImageData != null){ ImageDefault = ImageData.toString(); } cards item = new cards(dataSnapshot.getKey(), dataSnapshot.child("Name").getValue().toString() , ImageDefault);` This is the code . Its still showing the same error – Tech jd Nov 01 '19 at 06:16
  • That's mean you don't apply my solution. Please check my solution and let me know – Md. Asaduzzaman Nov 01 '19 at 09:33