我无法从Firebase(Java)获取特定数据

时间:2018-11-19 14:14:17

标签: java firebase firebase-realtime-database

我正在做一个应用程序,该应用程序需要进入Firebase以获取纬度和经度。我将Latlng放进火场中没有任何问题,但我无法收回。这是它的样子:

my firebase

这是我将它们放在Firebase中的代码

Ajouter.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            mProgress.setTitle("Le point se charge");
            mProgress.setMessage("Merci de patientez, ce ne sera pas long");
            mProgress.show();
            mAuth = FirebaseAuth.getInstance();
            FirebaseUser user = mAuth.getCurrentUser();
            mFirebaseDatabase = FirebaseDatabase.getInstance();
            mMarkDatabase = mFirebaseDatabase.getReference();
            final String key = mMarkDatabase.child("Pins").push().getKey();

            final StorageReference ref = mStorage.child("Photos/" + UUID.randomUUID().toString());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] data = baos.toByteArray();
            UploadTask uploadTask = ref.putBytes(data);
            uploadTask = ref.putFile(ImageUri);
            Task<Uri> urltask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                @Override
                public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }

                    return ref.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if (task.isSuccessful()) {

                        downloadUrl = task.getResult();
                        downloadUrlTxt = downloadUrl.toString();

                        //uploadImage();
                        String lon = Double.toString(Longitude);
                        String lat = Double.toString(Latitude);
                        String txt = TxtAout.getText().toString();
                        switch (spinner.getSelectedItemPosition()){
                            case 0 :
                                item.put("ImageUrl", ""+downloadUrlTxt);
                                item.put("Longitude ", lon);
                                item.put("Latitude", lat);
                                item.put("Description", txt);
                                mMarkDatabase.child("Pins").child("Poubelle").child(key).setValue(item);
                                break;
                            case 1 :
                                item.put("ImageUrl", ""+downloadUrlTxt);
                                item.put("Longitude ", lon);
                                item.put("Latitude", lat);
                                item.put("Description", txt);
                                mMarkDatabase.child("Pins").child("BlueLy").child(key).setValue(item);
                                break;
                            case 2 :
                                item.put("ImageUrl", ""+downloadUrlTxt);
                                item.put("Longitude ", lon);
                                item.put("Latitude", lat);
                                item.put("Description", txt);
                                mMarkDatabase.child("Pins").child("Parcs a chiens").child(key).setValue(item);
                                break;
                            case 3 :
                                item.put("ImageUrl", ""+downloadUrlTxt);
                                item.put("Longitude ", lon);
                                item.put("Latitude", lat);
                                item.put("Description", txt);
                                mMarkDatabase.child("Pins").child("Collecte de vetements").child(key).setValue(item);
                                break;
                            default :
                                Toast.makeText(LocalisationOnlyVert.this, "Erreur, merci de recommencer", Toast.LENGTH_SHORT).show();
                        }

                        mProgress.dismiss();
                        Toast.makeText(LocalisationOnlyVert.this, "Merci de votre ajout !", Toast.LENGTH_SHORT).show();
                        TxtAout.setText("");
                        Intent Retour = new Intent (LocalisationOnlyVert.this, OnlyVert.class);
                        startActivity(Retour);
                        Toast.makeText(LocalisationOnlyVert.this, ""+downloadUrlTxt , Toast.LENGTH_LONG).show();
                    }
                }
            });

        }
    });

我不知道如何分隔纬度,经度,描述和URL。我不知道该怎么办。

编辑:在您给我发送邮件之后,我尝试了:

BtnMarker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mDatabase = FirebaseDatabase.getInstance().getReference();
            mDatabase.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for(DataSnapshot snapshot: dataSnapshot.getChildren()){

                        HandleData.Pin pin = snapshot.getValue(HandleData.Pin.class);
                        Toast.makeText(OnlyVert.this, pin.getLat(), Toast.LENGTH_SHORT).show();

                    }


                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
}

错误是com.google.firebase.database.DatabaseException: Class com.example.alexandre.onlyvert.HandleData$Pin does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped.

2 个答案:

答案 0 :(得分:0)

使用下面的此类,它拥有您想要的一切

您可以使用此设置数据并跟踪事件

您可以使用它获取数据并再次跟踪事件

 public class HandleData {

    private OnDataSet onDataSet;
    private OnDataCallBack onDataCallBack;

    public void setOnDataSet(OnDataSet onDataSet) {
        this.onDataSet = onDataSet;
    }

    public void setOnDataCallBack(OnDataCallBack onDataCallBack) {
        this.onDataCallBack = onDataCallBack;
    }

    private FirebaseDatabase firebaseDatabase;

    public HandleData() {
        firebaseDatabase = FirebaseDatabase.getInstance();
    }

    public void putData(String specificNode, Pin pin){
        DatabaseReference databaseReference = firebaseDatabase.getReference("path/to/node/").child(specificNode);
        databaseReference.setValue(pin).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                if(onDataSet != null){
                    onDataSet.onSucess();
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                if(onDataSet != null){
                    onDataSet.onFailed(e.toString());
                }
            }
        });
    }

    public void readData(String specificNode){
        DatabaseReference databaseReference = firebaseDatabase.getReference("path/to/node/").child(specificNode);
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if(dataSnapshot.exists()){
                    int initCount = 0;
                    int totalCount = (int) dataSnapshot.getChildrenCount();
                    ArrayList<Pin> pins = new ArrayList<>();
                    for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                        initCount = initCount +1;
                        Pin pin = snapshot.getValue(Pin.class);
                        pins.add(pin);
                        if(initCount == totalCount){
                            if(onDataCallBack != null){
                                onDataCallBack.onSuccess(pins);
                            }
                        }

                    }
                }else{
                    if(onDataCallBack != null){
                        onDataCallBack.onFailed("no data found in database");
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                if(onDataCallBack != null){
                    onDataCallBack.onFailed(databaseError.toString());
                }
            }
        });
    }

    public class Pin{

        private String about;
        private String imgUrl;
        private String lat;
        private String lng;

        public Pin() {

        }

        public Pin(String about, String imgUrl, String lat, String lng) {
            this.about = about;
            this.imgUrl = imgUrl;
            this.lat = lat;
            this.lng = lng;
        }

        public String getAbout() {
            return about;
        }

        public void setAbout(String about) {
            this.about = about;
        }

        public String getImgUrl() {
            return imgUrl;
        }

        public void setImgUrl(String imgUrl) {
            this.imgUrl = imgUrl;
        }

        public String getLat() {
            return lat;
        }

        public void setLat(String lat) {
            this.lat = lat;
        }

        public String getLng() {
            return lng;
        }

        public void setLng(String lng) {
            this.lng = lng;
        }
    }

    public interface OnDataSet{
        void onSucess();
        void onFailed(String error);
    }

    public interface OnDataCallBack{
        void onSuccess(ArrayList<Pin> pins);
        void onFailed(String error);
    }

}

答案 1 :(得分:0)

您在这里有错字

item.put("Longitude ", lon);

将其更改为此

item.put("Longitude", lon);

因为那样会在Firebase结构上用“”推送键值,所以这就是为什么您无法获取该值的原因,因为地图需要键-值对才能工作,并且无法找到经度数据。

此外,更改此设置后,您将需要推送新值并删除数据库中错误的值

logcat异常在此处指出

double longitude = Double.parseDouble(map.get("Longitude"));

与此

  

java.util.Map具有通用类型参数

enter image description here

现在,获取数据。

据我了解,您需要按下一个按钮并从firebase的该节点中获取所有LatLang,假设您有 Poubelle 按钮,该按钮可从该节点获取所有纬度和经度,以这种方式完成。

        mDatabase = FirebaseDatabase.getInstance().getReference();
        DatabaseReference mPoubelleRef = mDatabase.child("Pins").child("Poubelle");

        BtnPoubelle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                mPoubelleRef.addValueEventListener(new ValueEventListener() {
          @Override
          public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot: dataSnapshot.getChildren()){
                 Map<String, String> map = snapshot.getValue(Map.class);
                            double latitude = Double.parseDouble(map.get("Latitude"));
                            double longitude = Double.parseDouble(map.get("Longitude"));

               //or get the data with a model (is the same thing as above)
               YourModel model = snapshot.getValue(YourModel.class);
               double latitude = model.getLatitude();
               double longitude = model.getLongitude();

               }
          }

          @Override
          public void onCancelled(DatabaseError databaseError) {
            System.out.println("The read failed: " + databaseError.getCode());
          }
        });
        }

检索数据之前,请先使用

删除节点
  

“经度”:

否则每次尝试获取数据时都会失败。