【问题标题】:How to read a specific value from each of the node in firebase?如何从firebase中的每个节点读取特定值?
【发布时间】:2018-12-02 14:38:57
【问题描述】:

我想在谷歌地图中显示一堆自定义标记(来自 com.google.maps.android:android-maps-utils:0.5 的 IconGenerator)。但是构建标记的数据,LatLong 位置在 firebase 数据库中,每个孩子都有自己的位置值,我如何读取每个孩子的位置并将其传递给将显示标记的类?

package com.realty.drake.kunuk;


import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Keep;

import com.google.android.gms.maps.model.LatLng;

/**
 * Created by drake on 5/1/18.
 * This class is the model class
 */
@Keep
public class Property implements Parcelable {
private int price;
private String address;
private int numberOfBed;
private int numberOfBath;
private int numberOfCar;
private String propertyImage;
private float lotDim;
private String propertyDesc;
private float propertyDim;
private String lotTerrainType;
private String lotTerrainDimExt;
private String lotTerrainSteepness;
private LatLng location;


public Property() { } //Needed for Firebase's auto data mapping

public Property(int price, String address, int numberOfBed, int numberOfBath,
                int numberOfCar, String propertyImage, float lotDim,
                String propertyDesc, float propertyDim, String lotTerrainType,
                String lotTerrainDimExt, String lotTerrainSteepness,
                LatLng location) {
    this.price = price;
    this.address = address;
    this.numberOfBed = numberOfBed;
    this.numberOfBath = numberOfBath;
    this.numberOfCar = numberOfCar;
    this.propertyImage = propertyImage;
    this.lotDim = lotDim;
    this.propertyDesc = propertyDesc;
    this.propertyDim = propertyDim;
    this.lotTerrainType = lotTerrainType;
    this.lotTerrainDimExt = lotTerrainDimExt;
    this.lotTerrainSteepness = lotTerrainSteepness;
    this.location = location;
}

protected Property(Parcel in) {
    price = in.readInt();
    address = in.readString();
    numberOfBed=in.readInt();
    numberOfBath = in.readInt();
    numberOfCar = in.readInt();
    propertyImage = in.readString();
    lotDim = in.readFloat();
    propertyDesc = in.readString();
    propertyDim = in.readFloat();
    lotTerrainType = in.readString();
    lotTerrainDimExt = in.readString();
    lotTerrainSteepness = in.readString();
    location = in.readParcelable(getClass().getClassLoader());
}

public static  final Creator<Property> CREATOR = new Creator<Property>() {
    @Override
    public Property createFromParcel(Parcel in) {
        return new Property(in);
    }

    @Override
    public Property[] newArray(int i) {
        return new Property[i];
    }
};

public int getPrice() {
    return price;
}
public void setPrice(int price) {
    this.price = price;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public int getNumberOfBed() {
    return numberOfBed;
}

public void setNumberOfBed(int numberOfBed) {
    this.numberOfBed = numberOfBed;
}

public int getNumberOfBath() {
    return numberOfBath;
}

public void setNumberOfBath(int numberOfBath) {
    this.numberOfBath = numberOfBath;
}

public int getNumberOfCar() {
    return numberOfCar;
}

public void setNumberOfCar(int numberOfCar) {
    this.numberOfCar = numberOfCar;
}

public String getPropertyImage() {
    return propertyImage;
}

public void setPropertyImage(String propertyImage) {
    this.propertyImage = propertyImage;
}

public float getLotDim() {
    return lotDim;
}

public void setLotDim(float lotDim) {
    this.lotDim = lotDim;
}

public String getPropertyDesc() {
    return propertyDesc;
}

public void setPropertyDesc(String propertyDesc) {
    this.propertyDesc = propertyDesc;
}

public float getPropertyDim() {
    return propertyDim;
}

public void setPropertyDim(float propertyDim) {
    this.propertyDim = propertyDim;
}

public String getLotTerrainType() {
    return lotTerrainType;
}

public void setLotTerrainType(String lotTerrainType) {
    this.lotTerrainType = lotTerrainType;
}

public String getLotTerrainDimExt() {
    return lotTerrainDimExt;
}

public void setLotTerrainDimExt(String lotTerrainDimExt) {
    this.lotTerrainDimExt = lotTerrainDimExt;
}

public String getLotTerrainSteepness() {
    return lotTerrainSteepness;
}

public void setLotTerrainSteepness(String lotTerrainSteepness) {
    this.lotTerrainSteepness = lotTerrainSteepness;
}

public LatLng getLocation() {
    return location;
}

public void setLocation(LatLng location) {
    this.location = location;
}




@Override
public  int describeContents(){
    return  0;
}

@Override
public void writeToParcel( Parcel dest, int flags){
    dest.writeInt(price);
    dest.writeString(address);
    dest.writeInt(numberOfBed);
    dest.writeInt(numberOfBath);
    dest.writeInt(numberOfCar);
    dest.writeString(propertyImage);
    dest.writeFloat(lotDim);
    dest.writeString(propertyDesc);
    dest.writeFloat(propertyDim);
    dest.writeString(lotTerrainType);
    dest.writeString(lotTerrainDimExt);
    dest.writeString(lotTerrainSteepness);
    dest.writeParcelable(location,flags);
}
}

使用模型类的Fragment,它从firebase数据库中获取数据,并且还具有详细视图的意图

package com.realty.drake.kunuk;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.CircularProgressDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.text.NumberFormat;
import java.util.Locale;


/**
 * Created by drake on 4/11/18
 */

public class Tab1Buy extends Fragment {
private DatabaseReference propertyRef;
private RecyclerView mPropertyRecyclerView;
FirebaseRecyclerAdapter<Property, PropertyViewHolder> mPropertyAdapter;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.property_tab, container, false);
    mPropertyRecyclerView = rootView.findViewById(R.id.property_recyclerView);
    return rootView;
}


//TODO Check internet and display error msg if internet down
@Override
public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mPropertyRecyclerView.hasFixedSize();
    mPropertyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    final ProgressBar progressBar = view.findViewById(R.id.progressBar);
    progressBar.setVisibility(View.VISIBLE);

    propertyRef = FirebaseDatabase.getInstance()
            .getReference()
            .child("Buy");
    propertyRef.keepSynced(true);

    // keyQuery - the Firebase location containing the list of keys to be found in dataRef
    //Query personQuery = propertyRef.orderByKey();


    FirebaseRecyclerOptions<Property> options =
            new FirebaseRecyclerOptions.Builder<Property>()
                    .setQuery(propertyRef, Property.class)
                    .build();

    mPropertyAdapter = new FirebaseRecyclerAdapter<Property, PropertyViewHolder>(options) {


        @Override
        // Bind the Property object to the ViewHolder PropertyHolder
        public void onBindViewHolder(@NonNull PropertyViewHolder holder,
                                     final int position, @NonNull final Property model) {
            holder.setPrice(model.getPrice());
            holder.setAddress(model.getAddress());
            holder.setNumberOfBed(model.getNumberOfBed());
            holder.setNumberOfBath(model.getNumberOfBath());
            holder.setNumberOfCar(model.getNumberOfCar());
            holder.setPropertyImage(model.getPropertyImage());

        //This Intent send Parcelable from Property to PropertyDetail
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().startActivity(new Intent(getActivity(), PropertyDetail.class)
                .putExtra("Property", model));

            }
        });


        }

        @Override
        public PropertyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            // Create a new instance of the ViewHolder, in this case we are using a custom
            // layout called R.layout.property_card for each item
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.property_card, parent, false);
            return new PropertyViewHolder(view);

        }

        @Override
        public void onDataChanged() {
            // Called each time there is a new data snapshot. You may want to use this method
            // to hide a loading spinner or check for the "no documents" state and update your UI.
            // ...
            progressBar.setVisibility(View.GONE);
        }

        //TODO Implement onError
        @Override
        public void onError(@NonNull DatabaseError e) {
            // Called when there is an error getting data. You may want to update
            // your UI to display an error message to the user.
            // ...
            progressBar.setVisibility(View.GONE);
            Toast.makeText(getActivity(), "DatabaseError", Toast.LENGTH_SHORT).show();
        }

    };
    mPropertyRecyclerView.setAdapter(mPropertyAdapter);



}

@Override
public void onStart() {
    super.onStart();
    mPropertyAdapter.startListening();
}

@Override
public void onStop() {
    super.onStop();
    mPropertyAdapter.stopListening();
}


public class PropertyViewHolder extends RecyclerView.ViewHolder {
    View mView;

    public PropertyViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setPrice(int price) {
        String currencyPrice = NumberFormat //Format the price variable in currency form
                .getCurrencyInstance(Locale.US)
                .format(price);
        TextView Price = mView.findViewById(R.id.post_price);
        Price.setText(currencyPrice);
    }

    public void setAddress(String address){
        TextView Address = mView.findViewById(R.id.post_address);
        Address.setText(String.valueOf(address));
    }

    public void setNumberOfBed(int numberOfBed){
        TextView NumberOfBed = mView.findViewById(R.id.post_bedroom);
        NumberOfBed.setText(String.valueOf(numberOfBed));
    }

    public void setNumberOfBath(int numberOfBath){
        TextView NumberOfBath = mView.findViewById(R.id.post_bathroom);
        NumberOfBath.setText(String.valueOf(numberOfBath));
    }

    public  void  setNumberOfCar(int numberOfCar) {
        TextView NumberOfCar = mView.findViewById(R.id.post_garage);
        NumberOfCar.setText(String.valueOf(numberOfCar));
    }

    public void setPropertyImage(String propertyImage){
        ImageView imageView = mView.findViewById(R.id.post_propertyImage);

        //take one long string containing multiple url in and parse it
        String propertyImageArray[] = propertyImage.split(",");

        //Loading circle for placeholder, ColorAccent has been used
        CircularProgressDrawable progressDrawable =
                new CircularProgressDrawable(getContext());
        progressDrawable.setStrokeWidth(5f);
        progressDrawable.setCenterRadius(30f);
        progressDrawable.setColorSchemeColors(Color.argb(1,255,145,0));
        progressDrawable.start();

        // Download directly from StorageReference using Glide
        // (See MyAppGlideModule for Loader registration)
        GlideApp.with(getContext())
                .load(propertyImageArray[0])
                .placeholder(progressDrawable)
                .fitCenter()
                .into(imageView);
    }
}

}

Tab1Buy 的意图调用的详细活动

package com.realty.drake.kunuk;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.MenuItem;
import android.widget.Toast;

import java.text.NumberFormat;
import java.util.Locale;


public class PropertyDetail extends AppCompatActivity implements Toolbar.OnMenuItemClickListener {


@Override
protected void onCreate( Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.property_detail);
    Toolbar myToolbar = (Toolbar) findViewById(R.id.kunuk_toolbar);
    myToolbar.inflateMenu(R.menu.menu_detail);
    setSupportActionBar(myToolbar);

    myToolbar.setOnMenuItemClickListener(this);

    //collect our intent
    Intent intent = getIntent();
    Property property = intent.getParcelableExtra("Property");
    boolean isRent = getIntent().getBooleanExtra("isRent", false);

    //collect all property values from Parcelable
    int price = property.getPrice();
    String address = property.getAddress();
    int numberOfBed = property.getNumberOfBed();
    int numberOfBath = property.getNumberOfBath();
    int numberOfCar = property.getNumberOfCar();
    String propertyImage = property.getPropertyImage();
    float propertyDim = property.getPropertyDim();
    String propertyDesc = property.getPropertyDesc();


    // Get a support ActionBar corresponding to this toolbar
    ActionBar ab = getSupportActionBar();

    // Enable the Up button
    ab.setDisplayHomeAsUpEnabled(true);

    BottomNavigationView bottomNavigationView = (BottomNavigationView)
            findViewById(R.id.bottom_navigation);

    bottomNavigationView.setOnNavigationItemSelectedListener(
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.action_call:
                            Uri callNumberUri = Uri.parse("tel:+50937438713");
                            Intent callIntent = new Intent(Intent.ACTION_DIAL, callNumberUri);
                            startActivity(callIntent);
                            break;
                        case R.id.action_sms:
                            Uri smsNumberUri = Uri.parse("sms:+50937438713");
                            Intent smsIntent = new Intent(Intent.ACTION_SENDTO, smsNumberUri);
                            startActivity(smsIntent);
                            break;
                        case R.id.action_email:
                            //TODO get a property id to use in subject email field
                            Intent emailIntent = new Intent(Intent.ACTION_SEND);
                            emailIntent.setType("message/rfc822");
                            emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Kunuk Request");
                            emailIntent.putExtra(Intent.EXTRA_EMAIL,
                                    new String[] {"drakecolinj@gmail.com"});
                            startActivity(emailIntent);
                    }
                    return false;
                }
            });

    //Bind the data from the Parcelable to the Views
    TextView addressDetail = findViewById(R.id.post_address);
    addressDetail.setText(String.valueOf(address));

    String currencyPrice = NumberFormat //Format the price variable in currency form
            .getCurrencyInstance(Locale.US)
            .format(price);
    TextView priceDetail = findViewById(R.id.post_price);
    priceDetail.setText(currencyPrice);

    ImageView imageView = findViewById(R.id.post_propertyImage);

    //take one long string containing multiple url and parse it
    String propertyImageArray[] = propertyImage.split(",");

    //TODO add loading icon for placeholder

    // Download directly from StorageReference using Glide
    // (See MyAppGlideModule for Loader registration)
    GlideApp.with(getApplication())
            .load(propertyImageArray[0])
            .fitCenter()
            .into(imageView);

    TextView bathroomDetail = findViewById(R.id.post_bathroom);
    bathroomDetail.setText(String.valueOf(numberOfBath));

    TextView bedroomDetail = findViewById(R.id.post_bedroom);
    bedroomDetail.setText(String.valueOf(numberOfBed));

    TextView garageDetail = findViewById(R.id.post_garage);
    garageDetail.setText(String.valueOf(numberOfCar));

    TextView propertyDimDetail = findViewById(R.id.property_dim);
    propertyDimDetail.setText(String.valueOf(propertyDim));

    TextView propertyDescDetail = findViewById(R.id.property_desc);
    propertyDescDetail.setText(String.valueOf(propertyDesc));

    if (isRent) {
        final TextView rentUnit = findViewById(R.id.rent_unit_detail);
        rentUnit.setVisibility(View.VISIBLE);
    }



}

@Override
public boolean onMenuItemClick(MenuItem item){
    switch (item.getItemId()) {
        case R.id.action_share:
            Toast.makeText(this, "Shared", Toast.LENGTH_SHORT).show();
            return true;
    }
    return true;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_detail, menu);
    return true;
}






}

在 Child "Buy" 中,每个孩子都有自己的 location key,对于 Rent 和 Lot 也是如此。

请帮忙,请概念解释和代码

【问题讨论】:

  • 您尝试过什么了吗?因为没有这个,这对于 Stack Overflow 上的问题来说太宽泛了,我建议从 Firebase documentationcodelab 开始。
  • 感谢@Frank van Puffelen。会调查的

标签: java android firebase-realtime-database google-maps-markers


【解决方案1】:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Buy");
databaseReference.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        // Let us retrieve value of location
        Log.i("Price", dataSnapshot.child("location").getValue().toString());
        // In this way you can retrieve all the fileds.
    }

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

同样地,对于 Rent & Lot,您可以传递为 -

DatabaseReference dbRent = FirebaseDatabase.getInstance().getReference("Rent");
DatabaseReference dbLot = FirebaseDatabase.getInstance().getReference("Lot");

我希望这会有所帮助!

【讨论】:

  • 感谢您的快速回复 Raj。但我想阅读“购买”拥有的每个孩子的“位置”字段。但是“Lot”和“Rent”与“Buy”的结构相同,我想阅读他们每个孩子的“location”字段。
  • 谢谢@Raj,我会调查它,并随时通知您。非常感谢回复
  • 我想做的是:做一个房地产应用。当您单击一个标记时,它应该显示一个带有相应房屋的片段。我想念大局
  • 是的,您可以通过该纬度、经度并显示房屋。
  • 刚刚上传了一张图片。这是一个带有一些cardview的recyclerview。当您单击卡片视图时,它会打开详细视图。 FAB 按钮打开带有标记的地图。它将填充来自 Buy、Rent、Lot 选项卡的所有标记。如何使用每个项目的位置并在 mapActivity 中显示它们,然后当您单击标记时,它应该打开该项目的详细视图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多