代码之家  ›  专栏  ›  技术社区  ›  Dr4ke the b4dass

如何从FireBase中的每个节点读取特定值?

  •  0
  • Dr4ke the b4dass  · 技术社区  · 6 年前
    导入android.os.package; /** 私人国际浴室数量; 私人浮动彩票; 私人浮动财产dim; string propertydesc,float propertydim,string lotterraintype, 拉丁语地点){ this.lottim=lottim; this.lotteraindimext=lotteraindimext; this.location=位置; propertyImage=in.readString(); propertyDim=in.readFloat(); @覆盖 public int getprice()。{ 公共无效设定价格(国际价格){ public void setaddress(字符串地址){ } 返回床位号; 公共空间设置浴室数量(内部浴室数量){ } this.numberofcar=车辆数量; 返回propertyimage; public void setpropertyimage(字符串propertyimage){ } } this.propertydesc=属性desc; 公共float getPropertyDim()。{ this.propertydim=属性dim; 返回lotterainType; 公共void setlotterainType(string lotterainType){ } 返回lotteraindimext; 返回lotterinsteepness; 公共void setlotterinsteepness(字符串lotterinsteepness){ } @覆盖 dest.writeString(地址); dest.writefloat(属性dim); } 导入android.content.intent; 导入android.os.bundle; 导入android.support.annotation.nullable; 导入android.support.v7.widget.recyclerview; 导入android.view.view; 导入android.widget.textview; 导入com.google.firebase.database.firebasedatabase; *德雷克于4/11/18创作 公共类tab1buy扩展片段{ private recyclerview mpropertyrecyclerview; @覆盖 //TODO检查Internet并在Internet关闭时显示错误消息 final progressbar progressbar=view.findviewbyid(r.id.progressbar); propertyRef=FireBaseDatabase.getInstance()。 .child(“购买”); //查询personquery=propertyRef.orderByKey(); 新建FireBaseRecyclerOptions.Builder<属性>() holder.setNumberofBed(model.getNumberofBed()); holder.setNumberofCar(model.getNumberofCar()); //此意图将parcelable从属性发送到propertydetail .putextra(“属性”,模型)); @覆盖 //创建新的Viewholder实例,在本例中,我们使用的是自定义 视图视图=layoutInflator.From(parent.getContext()) 返回新的propertyviewholder(view); //隐藏加载微调器或检查“无文档”状态并更新用户界面。 public void onerror(@nonnull databaseerror e){ //向用户显示错误消息的用户界面。 mpropertyadapter.stopListening(); 公共属性视图持有者(视图项视图){ mview=项目视图; .getcurrencyinstance(区域设置.us) } } textView numberofbed=mview.findView byid(r.id.post_卧室); } 公共空间设置浴室数量(内部浴室数量){ numberofbath.settext(string.valueof(numberofbath)); 公共空位设置车辆编号(国际车辆编号){ numberofcar.settext(string.valueof(numberofcar)); //获取一个包含多个URL的长字符串并对其进行分析 //已使用Placeholder、ColorAccent的加载圆 progressdrawable.start(); } }

    通过tab1buy的意图调用的详细活动

    导入android.content.intent; 导入android.support.annotation.nonnull; 导入android.support.v7.app.actionbar; 导入android.view.view; 创建时受保护的void(bundle savedinstanceState){ setContentView(r.layout.property_detail); mytoolbar.inflateMenu(r.menu.menu.detail); mytoolbar.setonmenuitemclicklistener(this); 意向=getIntent(); //从Parcelable收集所有属性值 字符串地址=property.getAddress(); string propertydesc=property.getpropertydesc(); actionBar ab=getSupportActionBar(); ab.setDisplayHomeAsupEnabled(真); findViewByID(r.id.bottom_导航); 新建BottomNavigationView.OnNavigationItemSelectedListener()。{ 休息; 意向smsintent=新意向(intent.action_sendto,smsnumberuri); 开始活动(smsinent); 休息; 案例R.ID.行动\电子邮件: //TODO获取要在主题电子邮件字段中使用的属性ID 意向emailintent=新意向(intent.action_send); emailintent.settype(“消息/rfc822”); emailintent.putextra(intent.extra_subject,“kunuk请求”); email intent.putextra(intent.extra_电子邮件, 新字符串[]“drakecolinj@gmail.com”); 开始活动(电子邮件意向); } 返回false; } })(二) //将parcelable中的数据绑定到视图 textView addressDetail=findView byid(r.id.post_地址); .getcurrencyinstance(区域设置.us) imageview imageview=findviewbyid(r.id.post propertyimage); //使用glide直接从storagereference下载 glideAppWith(getApplication()) .fitcenter()。 浴室细节。设置文本(字符串。值(浴室数量)); propertyDimDetail.settext(string.valueof(propertyDim)); toast.makeText(this,“shared”,toast.length_short).show(); } }

    enter image description here

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

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

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

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

    1 回复  |  直到 6 年前
        1
  •  2
  •   Raj    6 年前
    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) {
        }
    });
    

    同样,对于租金和地段,您可以通过-

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