2017-10-28 75 views
-3

當我嘗試從列表中獲取數據庫中的所有數據時,我從調試器中得到以下錯誤,代碼返回空列表。Firebase沒有這樣的實例字段'databaseReference'

public static DbOps get(Context ctx) { 
    if (sDbOps == null) { 
     sDbOps = new DbOps(ctx); 
    } 
    return sDbOps; 
} 

private DbOps(Context ctx) { 
    dbRef = FirebaseDatabase.getInstance().getReference().child("products"); 
    if(mProducts == null) { 
     getProducts(); 
    } 
} 



public List<Product> getProducts() { 
    dbRef.addValueEventListener(new ValueEventListener() { 
     @Override 
     public void onDataChange(DataSnapshot dataSnapshot) { 
      Iterator<DataSnapshot> iterator = dataSnapshot.getChildren().iterator(); 
      mProducts = new ArrayList<>(); 
      while (iterator.hasNext()) { 
       Product pr = dataSnapshot.getValue(Product.class); 
       mProducts.add(pr); 
      } 
     } 

     @Override 
     public void onCancelled(DatabaseError databaseError) { 

     } 
    }); 
    return mProducts; 
} 

image

+0

你在哪裏在構造函數中 –

+0

@SushinPv創建主類爲私有的DBREF變量並在OnCreate初始化() – Kristjan

+0

創建了'dbRef'變量 –

回答

0

的錯誤是因爲你trying to access a variable that is not declared in the scope of that function

爲了解決這個問題,一個簡單的解決方案是,將該變量作爲該類的私有或公共成員,以便所有成員函數都可以訪問它。

public class classname{ 
    private FirebaseDatabase dbRef; 

    @Override 
    public void onStart(Intent intent, int startid) { 
     dbRef = FirebaseDatabase.getInstance().getReference().child("products"); 
    } 

    //Or initialize in your own function 
    private DbOps(Context ctx) { 
     dbRef = FirebaseDatabase.getInstance().getReference().child("products"); 
     if(mProducts == null) { 
      getProducts(); 
     } 
    } 

    public List<Product> getProducts() { 
     dbRef.addValueEventListener(new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot dataSnapshot) { 
       Iterator<DataSnapshot> iterator = dataSnapshot.getChildren().iterator(); 
       mProducts = new ArrayList<>(); 
       while (iterator.hasNext()) { 
        Product pr = dataSnapshot.getValue(Product.class); 
        mProducts.add(pr); 
       } 
      } 

      @Override 
      public void onCancelled(DatabaseError databaseError) { 

      } 
     }); 
     return mProducts; 
    } 
} 
相關問題