firebase中的数据库如何获取特定信息并放入特定标记谷歌地图

时间:2016-07-03 09:54:14

标签: android firebase firebase-realtime-database

on on create我这样做:

  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        mDatabase = FirebaseDatabase.getInstance().getReference();

我在谷歌地图标记中使用,当用户想要保存另一个地方时,我成功地将标记完全放在用户选择的LATLNG上。但我有更多的信息,用户提出的地方名称,评级等... 并且我没有成功将信息放在使用添加的相同标记上。 在这里我从firebase数据库中添加标记:

    mDatabase.child("Bath").addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

        for (DataSnapshot data : dataSnapshot.getChildren());
            Bathroom bathroom=dataSnapshot.getValue(Bathroom.class);

            double locationSaveLat = bathroom.getLocationBathBLat();
            double locationSaveLon = bathroom.getLocationBathALon();


            mMap.addMarker(new MarkerOptions().position(new LatLng(locationSaveLon,locationSaveLat)).draggable(false).icon(BitmapDescriptorFactory
                    .fromResource(R.drawable.bath_small)).title(titleReadFragment));
            Log.d("data", bathroom.getRatebath());
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            Log.d("data change",dataSnapshot.toString());

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
            Log.d("data remove",dataSnapshot.toString());

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }


    });

这是我的片段类SaveBathroonFragment,我保存详细信息标记并推送到firebase。

在这里,我无法成功将信息添加到特定标记,它为所有标记提供了第一个信息,并且没有给我特定标记的具体信息。我认为需要循环,但我不知道究竟是怎么做的。

public class SaveBathroonFragment extends DialogFragment  {

    private static final String fireBase_URL="https://bathroomfinder.firebaseio.com/path/to/data";
    private DatabaseReference databaseReference;
    FirebaseStorage storage;
    StorageReference mountainsRef;
    private Activity context;
    private static int RESULT_LOAD_IMAGE = 2;
    private ArrayList<Bitmap> bitmapList=new ArrayList<Bitmap>();
    View view;
    private static Uri selectedImage;
    UploadTask uploadTask;
    InputStream inputStream;
    Bitmap bitmap;
    Handler handler;
    EditText locationLatitudeEditText;
    EditText locationLongitudeEditText;



    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
         databaseReference = FirebaseDatabase.getInstance().getReference();
         storage = FirebaseStorage.getInstance();


        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        double locationLON = getArguments().getDouble(MapsActivity.LON);
        double locationLAT = getArguments().getDouble(MapsActivity.LAT);


        builder.setMessage("Add new bathroom");
        view = context.getLayoutInflater().inflate(R.layout.save_bathroom_fragment, null, false);
        Button pickPhoto = (Button) view.findViewById(R.id.bpickphoto);
        pickPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TakePickphoto();
            }
        });
        AdapterImageView adapterImageView = new AdapterImageView(getActivity(), bitmapList);

        final EditText bathroomName = (EditText) view.findViewById(R.id.name_bath);

        builder.setView(view);

        locationLatitudeEditText = (EditText) view.findViewById(R.id.latitude_map);
        locationLongitudeEditText = (EditText) view.findViewById(R.id.longitude_map);
        locationLatitudeEditText.setText(locationLAT+"");
        locationLongitudeEditText.setText(locationLON+"");

        locationLongitudeEditText.setEnabled(false);
        locationLatitudeEditText.setEnabled(false);

        EditText rateBatroomEditText = (EditText) view.findViewById(R.id.rate_batroom);
        rateBatroomEditText.setEnabled(false);

        bathroomName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId== EditorInfo.IME_ACTION_SEND){
                    sendMessage();
                }
                return true;
            }
        });

        builder.setPositiveButton("Back", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setNegativeButton("Save", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                 sendMessage();

            }
        });

        return builder.create();
    }
    private void sendMessage() {
        EditText nameBathroomSave = (EditText) view.findViewById(R.id.name_bath);
        RatingBar rateBatroomSave = (RatingBar) view.findViewById(R.id.ratingBar);

        double locationBathBLat = Double.parseDouble(locationLatitudeEditText.getText().toString());
        double locationBathALon = Double.parseDouble(locationLongitudeEditText.getText().toString());
        String messageBath = nameBathroomSave.getText().toString();
        String rathbath = rateBatroomSave.getRating() + "";
        if (!messageBath.isEmpty()) {
            Random rand = new Random();

            String autor = "test" + rand.nextInt(1000);
            Bathroom bathroom = new Bathroom(autor, messageBath, rathbath, locationBathALon,locationBathBLat);
            if (databaseReference.child("Bath") != null) {
                if (databaseReference.child("Bath").child(autor) != null) {
                    databaseReference.child("Bath").child(autor).setValue(bathroom);
                    databaseReference.push().getDatabase();
                } else {
                    Toast.makeText(getActivity(), "missing some ", Toast.LENGTH_SHORT).show();
                }

这是我的类ReadBathroomFragment我在片段类中保存的内容,这个类也是片段

public class ReadBathroomFragment extends DialogFragment {
    private Activity context;
    GoogleMap mMap;
    private static LatLng locationDirectionClickOnMap;


    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {


        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();

        double locationLON = getArguments().getDouble(MapsActivity.LON);
        double locationLAT = getArguments().getDouble(MapsActivity.LAT);
        locationDirectionClickOnMap = new LatLng(locationLON,locationLAT);


//        builder.setTitle("Title");
        builder.setTitle("Bathroom details");
        //builder.setMessage("Bathroom details");
        View view = context.getLayoutInflater().inflate(R.layout.read_bathroom_fragment, null, false);
        builder.setView(view);
        final EditText placeName= (EditText) view.findViewById(R.id.name_read_bath);
        placeName.setEnabled(false);
        final EditText rateBatroomEditText = (EditText) view.findViewById(R.id.read_rate_batroom);
        rateBatroomEditText.setEnabled(false);
        final RatingBar readRating= (RatingBar) view.findViewById(R.id.read_ratingBath);
        readRating.setEnabled(true);
        EditText locationReadText = (EditText) view.findViewById(R.id.latlng_map_read);

        locationReadText.setText(locationLON + "," + locationLAT);
        //locationReadText.setText(Locationq);
        locationReadText.setEnabled(false);

        mDatabase.child("Bath").addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//                for (DataSnapshot data : dataSnapshot.getChildren());

                Bathroom bathroom = dataSnapshot.getValue(Bathroom.class);
                Log.d("children count", String.valueOf(dataSnapshot.getChildrenCount()));
                readRating.setRating(Float.parseFloat(bathroom.getRatebath()));
                placeName.setText(bathroom.getMessageNameBath());


            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                for (DataSnapshot data : dataSnapshot.getChildren());

                Bathroom bathroom=dataSnapshot.getValue(Bathroom.class);
                Log.d("children count", String.valueOf(dataSnapshot.getChildrenCount()));
                readRating.setRating(Float.parseFloat(bathroom.getRatebath()));
                placeName.setText(bathroom.getMessageNameBath());


            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });




        builder.setPositiveButton("Back", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setNegativeButton("Thank you", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });


        return builder.create();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.context = activity;

    }
}

这是我的浴室课

public class Bathroom {
    private String autor;
    private String messageNameBath;
    private String  ratebath;

    private double locationBathBLat;
    private double locationBathALon;

    public Bathroom() {
    }

    public double getLocationBathBLat() {
        return locationBathBLat;
    }

    public double getLocationBathALon() {
        return locationBathALon;
    }

    public String  getRatebath() {
        return ratebath;
    }

    public Bathroom(String autor, String messageNameBath, String ratebath
            ,double locationBathBLat,double locationBathALon) {
        this.autor = autor;
        this.messageNameBath = messageNameBath;
        this.ratebath=ratebath;
        this.locationBathBLat=locationBathBLat;
        this.locationBathALon=locationBathALon;


    }

    public String getAutor() {
        return autor;
    }

    public String getMessageNameBath() {
        return messageNameBath;
    }
}

1 个答案:

答案 0 :(得分:1)

您不需要自己生成ID(autor),只需使用push()生成具有唯一ID的新子项即可。 Firebase - Save Data on Android

Bathroom bathroom = new Bathroom(autor, messageBath, rathbath, locationBathALon,locationBathBLat);
databaseReference.child("Bath").push().setValue(bathroom);

您应该在OnMarkerClickListener

中实施ReadBathroomFragment
public class ReadBathroomFragment extends DialogFragment implements OnMarkerClickListener {

然后实现onMarkerClick方法来侦听标记点击事件

@Override
public boolean onMarkerClick(final Marker marker) {}

在从firebase数据库中读取数据后,您需要将Bathroom类和Marker保存到HashMap这样的数据结构中。因此,您不需要再次阅读firebase。

mDatabase.child("Bath").addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        Bathroom bathroom = dataSnapshot.getValue(Bathroom.class);

        double lat = bathroom.getLocationBathBLat();
        double lon = bathroom.getLocationBathALon();

        String messageName = bathroom.getMessageNameBath();
        String rate = bathroom.getRatebath();

        Marker marker = mMap.addMarker(new MarkerOptions()
            .position(new LatLng(lat,lon))
            .draggable(false)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.bath_small))
            .title(titleReadFragment)
            .snippet(messageName + " Rate: " + rate));
        markersMap.put(marker, bathroom);
    }

    @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) {}
});

不要忘记将HashMap变量声明为ReadBathroomFragment类变量

private Map<Marker, Bathroom> markersMap = new HashMap<>();

然后你可以在onMarkerClick方法中显示你的alertdialog,在看完所有视图后你应该setView

Bathroom bathroom = markersMap.get(marker);

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Bathroom details");

View view = context.getLayoutInflater().inflate(R.layout.read_bathroom_fragment, null, false);

EditText placeName = (EditText) view.findViewById(R.id.name_read_bath);
placeName.setEnabled(false);
placeName.setText(bathroom.getMessageNameBath());

EditText rateBatroomEditText = (EditText) view.findViewById(R.id.read_rate_batroom);
rateBatroomEditText.setEnabled(false);
rateBatroomEditText.setText(SOME_STRING);

RatingBar readRating = (RatingBar) view.findViewById(R.id.read_ratingBath);
readRating.setEnabled(true);
readRating.setRating(Float.parseFloat(bathroom.getRatebath()));

EditText locationReadText = (EditText) view.findViewById(R.id.latlng_map_read)
locationReadText.setText(SOME_STRING);

builder.setView(view);
builder.create().show();

我希望我回答你的问题,欢呼:)