访问firebase数据库中的分层节点?

时间:2018-01-19 14:57:34

标签: android firebase firebase-realtime-database

Helo,我想从firebase数据库的层次结构中的Coupon节点(如下图所示)获取每张优惠券的优惠券详细信息。 enter image description here

我想从Coupon节点检索所有优惠券并在列表视图中显示.. 我正在尝试使用此代码来获取数据库引用,但每次都获取null引用..

 FirebaseDatabase database = FirebaseDatabase.getInstance();
    myRef = database.getReference("VendorDtl").child("vendor1").child("Coupons");

我也试过..

FirebaseDatabase database = FirebaseDatabase.getInstance();
    myRef = database.getReference().child("VendorDtl").child("vendor1").child("Coupons");

但每次我都无法正确引用数据库.. 因此,列表视图显示但具有空值..

这是部署用于获取值的代码..

   protected void onStart() {
    super.onStart();
    //attaching value event listener
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            //clearing the previous artist list
            cpnlist.clear();

            //iterating through all the nodes
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                Log.i("valueeventDb","tHIS IS CALLED");
                //getting artist
                CouponDetails coups= ds.getValue(CouponDetails.class);
                //adding artist to the list
                cpnlist.add(coups);           
            }

            //creating adapter
            CouponAdp cpnAdp = new CouponAdp(ShowCoupons.this, cpnlist);
            //attaching adapter to the listview
            couplist.setAdapter(cpnAdp);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(getApplicationContext(),"EROrrr Fetching value ... ",Toast.LENGTH_SHORT).show();
        }
    });
}

这是适配器代码..

public class CouponAdp extends ArrayAdapter<CouponDetails> {
private Activity context;
List<CouponDetails> shpsv;

public CouponAdp(Activity context, List<CouponDetails> objects) {
    super(context,R.layout.item_list,objects);
    this.context=context;
    this.shpsv=objects;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {


    if (convertView == null) {
        convertView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.item_list, parent, false);
    }

    TextView coupNm = (TextView) convertView.findViewById(R.id.textView13);
    TextView coupDesc = (TextView) convertView.findViewById(R.id.textView15);
    TextView coupSts = (TextView) convertView.findViewById(R.id.textView17);
    TextView coupValidity = (TextView) convertView.findViewById(R.id.textView19);
    TextView coupValue = (TextView) convertView.findViewById(R.id.textView21);
    TextView coupCatg = (TextView) convertView.findViewById(R.id.textView23);

   CouponDetails shp=shpsv.get(position);

    coupNm.setText(shp.getScnm());
    coupDesc.setText(shp.getScdesc());
    coupSts.setText(shp.getScsts());
    coupValidity.setText(shp.getScval_from()+" to "+shp.getScval_to());
    coupValue.setText(shp.getSc_percentage());
    coupCatg.setText(shp.getSc_catg());

    return convertView;

}

如何正确获取优惠券详情并在列表视图上显示详细信息?

虽然我的应用程序直接显示任何错误! logcat显示......

    01-19 21:02:58.502 27083-28252/com.example.vendorapp V/FA: Connection attempt already in progress
01-19 21:02:58.547 27083-27083/com.example.vendorapp W/View: requestLayout() improperly called by android.support.v7.widget.AppCompatTextView{522cae9 V.ED..... ......ID 103,94-256,143 #7f08002a app:id/bb_bottom_bar_title} during layout: running second layout pass
01-19 21:02:58.547 27083-27083/com.example.vendorapp W/View: requestLayout() improperly called by android.support.v7.widget.AppCompatTextView{2d9936e V.ED..... ......ID 40,94-319,143 #7f08002a app:id/bb_bottom_bar_title} during layout: running second layout pass
01-19 21:02:58.547 27083-27083/com.example.vendorapp W/View: requestLayout() improperly called by android.support.v7.widget.AppCompatTextView{6a37a0f V.ED..... ......ID 107,94-251,143 #7f08002a app:id/bb_bottom_bar_title} during layout: running second layout pass
01-19 21:02:58.551 27083-27092/com.example.vendorapp I/zygote64: Do partial code cache collection, code=121KB, data=108KB
01-19 21:02:58.552 27083-27092/com.example.vendorapp I/zygote64: After code cache collection, code=121KB, data=108KB
01-19 21:02:58.552 27083-27092/com.example.vendorapp I/zygote64: Increasing code cache capacity to 512KB
01-19 21:02:58.553 27083-27092/com.example.vendorapp I/zygote64: Compiler allocated 8MB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
01-19 21:02:58.567 27083-28252/com.example.vendorapp D/FA: Connected to remote service
01-19 21:02:58.567 27083-28252/com.example.vendorapp V/FA: Processing queued up service tasks: 4
01-19 21:03:03.050 27083-28252/com.example.vendorapp V/FA: Recording user engagement, ms: 4583
01-19 21:03:03.051 27083-28252/com.example.vendorapp V/FA: Activity paused, time: 264940263
01-19 21:03:03.056 27083-28252/com.example.vendorapp D/FA: Logging event (FE): user_engagement(_e), Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=4583, firebase_screen_class(_sc)=Promotion, firebase_screen_id(_si)=7031206903639617093}]
01-19 21:03:03.076 27083-27083/com.example.vendorapp V/FA: onActivityCreated
01-19 21:03:03.145 27083-27092/com.example.vendorapp I/zygote64: Compiler allocated 4MB to compile void android.view.View.<init>(android.content.Context, android.util.AttributeSet, int, int)
01-19 21:03:03.165 27083-28252/com.example.vendorapp V/FA: Activity resumed, time: 264940378
01-19 21:03:03.169 27083-28252/com.example.vendorapp D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=Promotion, firebase_previous_id(_pi)=7031206903639617093, firebase_screen_class(_sc)=Coupons, firebase_screen_id(_si)=7031206903639617094}]
01-19 21:03:03.242 27083-27083/com.example.vendorapp W/View: requestLayout() improperly called by android.support.v7.widget.AppCompatTextView{b514d73 V.ED..... ......ID 103,94-256,143 #7f08002a app:id/bb_bottom_bar_title} during layout: running second layout pass
01-19 21:03:03.242 27083-27083/com.example.vendorapp W/View: requestLayout() improperly called by android.support.v7.widget.AppCompatTextView{1293430 V.ED..... ......ID 40,94-319,143 #7f08002a app:id/bb_bottom_bar_title} during layout: running second layout pass
01-19 21:03:03.243 27083-27083/com.example.vendorapp W/View: requestLayout() improperly called by android.support.v7.widget.AppCompatTextView{99208a9 V.ED..... ......ID 107,94-251,143 #7f08002a app:id/bb_bottom_bar_title} during layout: running second layout pass
01-19 21:03:03.258 27083-27092/com.example.vendorapp I/zygote64: Do full code cache collection, code=249KB, data=183KB
01-19 21:03:03.259 27083-27092/com.example.vendorapp I/zygote64: After code cache collection, code=240KB, data=145KB
01-19 21:03:03.334 27083-27220/com.example.vendorapp D/OpenGLRenderer: endAllActiveAnimators on 0x78bc848400 (RippleDrawable) with handle 0x78bdfc88a0
01-19 21:03:04.158 27083-28252/com.example.vendorapp V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 994
01-19 21:03:04.159 27083-28252/com.example.vendorapp V/FA: Activity paused, time: 264941372
01-19 21:03:04.185 27083-27083/com.example.vendorapp V/FA: onActivityCreated
01-19 21:03:04.211 27083-27083/com.example.vendorapp E/ANDR-PERF-JNI: IPerf::tryGetService failed!
01-19 21:03:04.306 27083-27083/com.example.vendorapp I/DynamiteModule: Considering local module com.google.android.gms.firebase_database:4 and remote module com.google.android.gms.firebase_database:6
01-19 21:03:04.306 27083-27083/com.example.vendorapp I/DynamiteModule: Selected remote version of com.google.android.gms.firebase_database, version >= 6
01-19 21:03:04.344 27083-27083/com.example.vendorapp W/zygote64: Skipping duplicate class check due to unrecognized classloader
01-19 21:03:04.387 27083-28252/com.example.vendorapp V/FA: Activity resumed, time: 264941600
01-19 21:03:04.392 27083-28252/com.example.vendorapp D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=Coupons, firebase_previous_id(_pi)=7031206903639617094, firebase_screen_class(_sc)=ShowCoupons, firebase_screen_id(_si)=7031206903639617095}]
01-19 21:03:04.411 27083-28380/com.example.vendorapp D/NetworkSecurityConfig: No Network Security Config specified, using platform default
01-19 21:03:04.543 27083-27220/com.example.vendorapp D/OpenGLRenderer: endAllActiveAnimators on 0x78ba5afc00 (RippleDrawable) with handle 0x78d611cb40
01-19 21:03:05.840 27083-27092/com.example.vendorapp I/zygote64: Do partial code cache collection, code=249KB, data=169KB
01-19 21:03:05.841 27083-27092/com.example.vendorapp I/zygote64: After code cache collection, code=249KB, data=169KB
01-19 21:03:05.841 27083-27092/com.example.vendorapp I/zygote64: Increasing code cache capacity to 1024KB
01-19 21:03:06.508 27083-27083/com.example.vendorapp I/valueeventDb: tHIS IS CALLED
01-19 21:03:06.522 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponCategory found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.523 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponStatus found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.523 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponName found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.523 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponValue found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.523 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponDesc found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.523 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponvalidFrom found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.523 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponvalidTo found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.532 27083-27083/com.example.vendorapp I/valueeventDb: tHIS IS CALLED
01-19 21:03:06.532 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponCategory found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.533 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponStatus found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.533 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponName found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.533 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponValue found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.533 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponDesc found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.533 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponvalidFrom found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.533 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponvalidTo found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.541 27083-27083/com.example.vendorapp I/valueeventDb: tHIS IS CALLED
01-19 21:03:06.542 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponCategory found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.542 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponStatus found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.542 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponName found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.542 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponValue found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.542 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponDesc found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.542 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponvalidFrom found on class com.example.vendorapp.CouponDetails
01-19 21:03:06.542 27083-27083/com.example.vendorapp W/ClassMapper: No setter/field for CouponvalidTo found on class com.example.vendorapp.CouponDetails
01-19 21:03:09.477 27083-28252/com.example.vendorapp V/FA: Inactivity, disconnecting from the service

2 个答案:

答案 0 :(得分:1)

要解决此问题,请使用以下代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference couponsRef = rootRef.child("VendorDtl").child("vendor1").child("Coupons");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<CouponDetails> cpnlist = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            CouponDetails coups = ds.getValue(CouponDetails.class);
            cpnlist.add(coups);
            Log.d("TAG", coups.getCouponName());
        }
        couplist.setAdapter(cpnAdp);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
couponsRef.addListenerForSingleValueEvent(eventListener);

正如您所看到的,我已在cpnlist方法中声明并使用onDataChange(),否则始终为null,因为它的异步行为。

修改

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference couponsRef = rootRef.child("VendorDtl").child("vendor1").child("Coupons");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<CouponDetails> cpnlist = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String couponCategory = ds.child("CouponCategory").getValue(String.class);
            String couponDesc = ds.child("CouponDesc").getValue(String.class);
            String couponName= ds.child("CouponName").getValue(String.class);
            String couponStatus = ds.child("CouponStatus").getValue(String.class);
            String couponValue = ds.child("CouponValue").getValue(String.class);
            String couponValidFrom = ds.child("CouponvalidFrom").getValue(String.class);
            String couponValidTo = ds.child("CouponValidTo").getValue(String.class);

            CouponDetails shp = new CouponDetails(couponCategory, couponDesc, couponName, couponStatus, couponValue, couponValidFrom, couponValidTo);
            cpnlist.add(shp);
            Log.d("TAG", couponName);
        }
        couplist.setAdapter(cpnAdp);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
couponsRef.addListenerForSingleValueEvent(eventListener);

答案 1 :(得分:0)

尝试使用此代码获取优惠券:

public class ActivityClassName extends AppCompatActivity {
    ArrayList<CouponDetails> couponDetailsArrayList;
    FirebseDatabase database;
    ListView couponListView;
    CouponAdp couponAdp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_activity_layout_id);

        couponDetailsArrayList = new ArrayList<>();
        database = FirebaseDatabase.getInstance();
        couponListView = findViewbyId(R.id.your_list_view_id);
        couponAdp = new CouponAdp(ActivityClassName.this,couponDetailsArrayList);

        getCoupons();

    }

    private void getCoupons(){
        couponDetailsArrayList.clear();
        DatabaseReference vendorGroup = database.getReference("VendorDtl");
        vendorGroup.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // for each vendor get inside the block(node)
                for (DataSnapshot snapshot : dataSnapshot.getChildren())
                    // inside each vendor get all the coupons
                    for(DataSnapshot coupon : snapshot.child("Coupons").getChildren());
                        couponDetailsArrayList.add(coupon.getValue(CouponDetails.class));
                couponAdp.notifyDataSetChanged();
                couponListView.setAdapter(couponAdp);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.i("CouponFetchError: ",databaseError.getMessage();
            }
        });
    }
}

此处 addValueEventListener()功能将持续监控在线数据库并实时更改 couponListView 的内容。删除侦听器是一种很好的做法,但Firebase客户端会在活动被破坏后自动处理它。

如果您想避免持续监控并希望只监控一次并获取数据并随时重复获取数据,则替换

vendorGroup.addValueEventListener(new ValueEventListener() {

vendorGroup.addListenerForSingleValueEvent(new ValueEventListener() {

Refer here for more details

并通过调用函数随时获取详细信息:

getCoupons();

希望这有效!!