0

When I want to retrieve data from FirebaseDatabase for showing them to users, allowing them to modify their inputs.

I get java.lang.NullPointerException errors as followings:

It's strange. Even I checked the firebaseDatabse, the inputs already are there under each use's unique ID.

Please help me to solve this problem, and tell me the reason why. Your kindly help are highly appreciated.

FATAL EXCEPTION: main
Process: com.comli.loyalfine.myfirstgooglemapapplication, PID:16262 java.lang.NullPointerException 
at com.comli.loyalfine.myfirstgooglemapapplication.ParkingSpaceRegisterActivity$12.onDataChange(ParkingSpaceRegisterActivity.java:495)
at com.firebase.client.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:56)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5335)
at java.lang.reflect.Method.invokeNative(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)

Following are my codes

public void ReadAndDisplayData() {
    mDatabaseRef= FirebaseDatabase.getInstance().getReference();
    mDatabaseRef.child("Parking Space Data").child("Not Verified").child(userId).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ParkingSpaceData post = null;

            post = dataSnapshot.getValue(ParkingSpaceData.class);
            assert post != null;
            System.out.print("etParkingSpaceAddress is "+post.getParkingAddress().toString());
            System.out.print("etLatLgn is "+post.getLatlng().toString());
            System.out.print("entranceuri is "+post.getIvParkingSpaceEntranceUri().toString());

            StorageReference fileRef = storageRef.child(userId).child("image").child(post.getEntranceRef());
            System.out.print("file uri is " +fileRef.getDownloadUrl().toString());
            ivParkingSpaceEntranceUri = post.getIvParkingSpaceEntranceUri();
            ivCertificateOfOwnershipUri = post.getIvCertificateOfOwnershipUri();
            vvVideoOfEntranceToParkingSpaceUri = post.getVvVideoOfEntranceToParkingSpaceUri();

            //Toast.makeText(ParkingSpaceRegisterActivity.this,"entranceuri is "+post.getIvParkingSpaceEntranceUri().toString(), Toast.LENGTH_LONG).show();
            // Toast.makeText(ParkingSpaceRegisterActivity.this,"file uri is " +fileRef.getDownloadUrl().toString(),Toast.LENGTH_LONG).show();
            //Picasso.with(ParkingSpaceRegisterActivity.this).load(ivParkingSpaceEntranceUri).fit().centerCrop().into(ivParkingSpaceEntrance);
            assert fileRef != null;
            fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    Picasso.with(ParkingSpaceRegisterActivity.this).load(uri).fit().centerCrop().into(ivParkingSpaceEntrance);
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Handle any errors
                }
            });
            fileRef = storageRef.child(userId).child("image").child(post.getOwnershipRef());
            fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    Picasso.with(ParkingSpaceRegisterActivity.this).load(uri).fit().centerCrop().into(ivCertificateOfOwnership);
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Handle any errors
                }
            });
            fileRef = storageRef.child(userId).child("video").child(post.getVideoRef());
            fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    vvVideoOfEntranceToParkingSpace.setBackgroundResource(0);
                    vvVideoOfEntranceToParkingSpace.setVideoURI(uri);
                    vvVideoOfEntranceToParkingSpace.start();
                    vvVideoOfEntranceToParkingSpace.pause();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Handle any errors
                }
            });
            etParkingSpaceAddress.setText(post.getParkingAddress(), TextView.BufferType.EDITABLE);
            etLatLgn.setText(post.getLatlng(), TextView.BufferType.EDITABLE);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            // Getting Post failed, log a message
            Toast.makeText(ParkingSpaceRegisterActivity.this, "loadPost:onCancelled" + databaseError.toException().getMessage(), Toast.LENGTH_LONG).show();
            // ...
        }
    });
}

The data structure listed in FirebaseDataBase as folloiwngs:

{"ParkingSpace" : 
   {"Not Verified" : 
     {"0vmf1Xc2M2SOYIyFCQz0YFouVH43" :  
       {"entranceRef" : "ivParkingSpaceEntrance.jpg",
        "latlng" : "lat/lng: (25.02859848016432,121.51109274476765)",
        "myMarkerPosition" : 
         {"latitude" : 25.02859848016432,
          "longitude" : 121.51109274476765},
        "ownershipRef" : "ivCertificateOfOwnership.jpg",
        "parkingAddress" : "xxxxxxxxxxxxxxxxxxxxxx",
        "videoRef" : "vvVideoOfEntranceToParkingSpace.mp4" },
    "61JSQnynNWRlN8CxAloEeYOSAxq2" : 
      {"entranceRef" : "ivParkingSpaceEntrance.jpg",
       "latlng" : "lat/lng: (25.028682934478617,121.51116415858267)",
       "myMarkerPosition" : 
         {"latitude" : 25.028682934478617,
          "longitude" : 121.51116415858267},
       "ownershipRef" : "ivCertificateOfOwnership.jpg",
       "parkingAddress" : "xxxxxxxxxxxxxxxxxxxxxx",
       "videoRef" : "vvVideoOfEntranceToParkingSpace.mp4"},
    "HE7UhdnQKjhvHSD3l7QNtQxoElw1" : 
      {"entranceRef" : "ivParkingSpaceEntrance.jpg",
       "latlng" : "lat/lng: (24.797805577018096,120.9950752928853)",
       "myMarkerPosition" : 
        {"latitude" : 24.797805577018096,
         "longitude" : 120.9950752928853},
       "ownershipRef" : "ivCertificateOfOwnership.jpg",
       "parkingAddress" : "xxxxxxxxxxxxxxxxxxxxxx",
       "videoRef" : "vvVideoOfEntranceToParkingSpace.mp4"},

As for ParkingSpaceData.class is as followings:

public class ParkingSpaceData {
  String parkingAddress;
  String latlng;
  LatLng myMarkerPosition;
  String entranceRef;
  String ownershipRef;
  String videoRef;
  Uri ivParkingSpaceEntranceUri, ivCertificateOfOwnershipUri , vvVideoOfEntranceToParkingSpaceUri;

  public ParkingSpaceData() {}  
  public String getEntranceRef() {return entranceRef;}
  public void setEntranceRef(String entranceRef) {this.entranceRef = entranceRef;}
  public String getLatlng() {return latlng;}
  public void setLatlng(String latlng) {this.latlng = latlng;}
  public LatLng getMyMarkerPosition() {return myMarkerPosition;}
  public void setMyMarkerPosition(LatLng myMarkerPosition) {this.myMarkerPosition = myMarkerPosition;}
  .
  .
  .//getters and setters
  .
  public Uri getIvCertificateOfOwnershipUri() {return ivCertificateOfOwnershipUri;}
  public void setIvCertificateOfOwnershipUri(Uri ivCertificateOfOwnershipUri){this.ivCertificateOfOwnershipUri = ivCertificateOfOwnershipUri;}
  .
  .
  .
Loyal Fine
  • 115
  • 2
  • 7
  • The error is caused on line `ParkingSpaceRegisterActivity.java:495`. I'd run the code in a debugger and see where the exception is raised. One of the values on that line is `null`. – Frank van Puffelen Sep 24 '16 at 20:47
  • that's a System.Out.Println to show the null position, in which post.getParkingAddress() is null. However, there is already a value in the firebasedatabase. – Loyal Fine Sep 24 '16 at 20:56
  • Can you update your question to include a minimal sample of the JSON structure (as text, no screenshot) at `Parking Space Data/Not Verified/$userId`? It would also be good if you could reduce the code to the minimum code that still causes the crash. – Frank van Puffelen Sep 24 '16 at 21:07
  • Just attached sample of JSON – Loyal Fine Sep 24 '16 at 21:32
  • Ouch, that's looks like a weirdly nested JSON structure. I doubt your `ParkingSpaceData` class handles them, but it's hard to be certain without seeing this class. Also: please reduce the amount of code and JSON to the minimum that is needed to reproduce the problem. That will make it easier to help you. – Frank van Puffelen Sep 24 '16 at 21:43
  • I'd really love to help, but there's simply to many things here for me to parse efficiently and the JSON looks invalid (you can get valid JSON by exporting it from your Firebase Database Console). Please provide the [minimal JSON and code that are needed to reproduce the problem](http://stackoverflow.com/help/mcve) (read that page, it explains how to do that and why it helps both of us). – Frank van Puffelen Sep 25 '16 at 03:04
  • 3 sets JSON attached. Thanks for your time to help! – Loyal Fine Sep 25 '16 at 05:31

2 Answers2

0
System.out.print("etParkingSpaceAddress is "+post.getParkingAddress().toString());
System.out.print("etLatLgn is "+post.getLatlng().toString());
System.out.print("entranceuri is "+post.getIvParkingSpaceEntranceUri().toString());

Remove all the .toString() calls from this code. If the item isn't null they are redundant, and if it is null they cause NPEs.

System.out.print("etParkingSpaceAddress is "+post.getParkingAddress());
System.out.print("etLatLgn is "+post.getLatlng());
System.out.print("entranceuri is "+post.getIvParkingSpaceEntranceUri());
user207421
  • 305,947
  • 44
  • 307
  • 483
-1

In your readAndDisplayData() method under on DataChanged.

Chage this:

ParkingSpaceData post = null; 
post=dataSnapshot.getValue(ParkingSpaceData.class);

To this:

dataSnapshot.getValue(new ParkingSpaceData.class);

And see if you still get same error. I am always sceptical about initializing such objects locally with null. This might not be a perfect solution but many a times it does solve such null errors. Moreover most firebase examples encourage the later way to retrieve data.

Please let me know if it changes anything for you.

EDIT - in your scenario it will work like:

ParkingSpaceData post = dataSnapshot.getValue(ParkingSpaceData.class);

This should compile. My whole point was to avoid initializing it with null. Try this please.

Nishant Dubey
  • 2,802
  • 1
  • 13
  • 18
  • The suggested code doesn't even compile, let alone have a rational explanation. – user207421 Sep 25 '16 at 02:58
  • I forgot to make point of the fact that I missed the actual post variable which is used to actually get data. Sorry for that mistake. Hopefully the suggested edit will compile. – Nishant Dubey Sep 25 '16 at 03:06
  • So why not remove the part that doesn't? And how is the newly suggested code going to change anything? Still no rational explanation. I agree with you about the futility of the initialization to null, but it doesn't cause this problem. – user207421 Sep 25 '16 at 03:08
  • Thanks for your input, but it doesn't work. The cause is unclear. – Loyal Fine Sep 25 '16 at 05:10