在RecyclerView中的Firebase数据库参考侦听器上禁用“喜欢”按钮

时间:2018-08-04 19:27:34

标签: android firebase firebase-realtime-database android-recyclerview

我的RecyclerView项目中有一个“喜欢”按钮。从Firebase数据库参考侦听器获取值。如果“计数”值为1,则该按钮应针对该特定列表项而被禁用,并将其颜色变为绿色。这是代码:

//segregate email to userID
    String[] emailSegregate = sharedPreferences.getString("email", "anonymous").split("@");
    String emailID = emailSegregate[0];

    //Check username has liked the post already or not
    mMessagesDatabaseReferenceCheck
            .child(emailID)
            .child(objectFile.getnodeId())
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    int b = 0;
                    check_counter objCheck = dataSnapshot.getValue(check_counter.class);
                    b = objCheck.getCount();
                    if (dataSnapshot.getChildrenCount() > 0) { // TODO: write this condition
                        //make it green
                        btnLike.setTypeface(null, Typeface.BOLD);
                        btnLike.setTextColor(Color.parseColor("#006400"));
                        btnLike.setEnabled(false);
                    }
                    else {}
                }

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

这是数据库:

enter image description here

无法从数据库中获取一个数据,并检查是否有条件禁用该特定nodeId listItem的按钮。

已编辑

这是例外-

E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.example.abhin.myapplication, PID: 13674
  java.lang.NullPointerException: Attempt to invoke virtual method 'int com.example.abhin.myapplication.check_counter.getCounter()' on a null object reference
      at com.example.abhin.myapplication.postAdapter$2.onDataChange(postAdapter.java:148)
      at com.google.firebase.database.zzp.onDataChange(Unknown Source)
      at com.google.android.gms.internal.firebase_database.zzfc.zza(Unknown Source)
      at com.google.android.gms.internal.firebase_database.zzgx.zzdr(Unknown Source)
      at com.google.android.gms.internal.firebase_database.zzhd.run(Unknown Source)
      at android.os.Handler.handleCallback(Handler.java:739)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:148)
      at android.app.ActivityThread.main(ActivityThread.java:5539)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找这样的东西:

public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    long count = dataSnapshot.child("count").getValue(Long.class);
    if (count > 0) {
        ...