无法从firebase检索数据以显示修改字段中的用户,android Java中的java.lang.NullPointerException

时间:2016-09-24 19:23:18

标签: java android firebase nullpointerexception

当我想从FirebaseDatabase检索数据以向用户展示时,允许他们修改输入。

我得到java.lang.NullPointerException错误如下:

很奇怪。即使我检查了firebaseDatabse,每个用户的唯一ID下输入已经存在。

请帮我解决这个问题,并告诉我原因。 非常感谢您的帮助。

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)

以下是我的代码

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();
            // ...
        }
    });
}

FirebaseDataBase中列出的数据结构如下:

{"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"},

至于ParkingSpaceData.class如下:

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

2 个答案:

答案 0 :(得分: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());

从此代码中删除所有.toString()次调用。如果该项不为null,则它们是多余的,如果它为null,则它们会导致NPE。

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

答案 1 :(得分:-1)

在DataChanged下的readAndDisplayData()方法中。

Chage this:

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

对此:

dataSnapshot.getValue(new ParkingSpaceData.class);

看看你是否仍然得到同样的错误。我总是对使用null在本地初始化这些对象持怀疑态度。这可能不是一个完美的解决方案,但很多时候它确实解决了这样的空错误。此外,大多数firebase示例都鼓励以后的方法来检索数据。

如果有任何改变,请告诉我。

编辑 - 在您的方案中,它的工作方式如下:

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

这应该编译。我的全部观点是避免用null初始化它。请试试这个。