在检索数据

时间:2017-05-01 09:21:02

标签: android firebase firebase-realtime-database

我搜索了分配但无法得到答案。我有 firebase 数据库。我正在检索所有数据并在listview中显示。为此,我使用的是 addValueEventListener ,但是OnDataChange没有执行,结果是null ArrayList,它给出了 NullPointer错误。如果有人可以帮助我,将不胜感激。提前致谢! enter image description here

RecipesDisplay:

    ListView list;
DatabaseReference mDatabaseRef;
FirebaseDatabase mRef;
String[]t;
int[] im;
ArrayList<Recipe> recipes = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_recipes_display);
    list = (ListView) findViewById(R.id.listview);
    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    mDatabaseRef = database.getReference("https://fir-practice-
    41da3.firebaseio.com/New Recipes/");

    mDatabaseRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
           recipes = new ArrayList<>();
            for (DataSnapshot msgSnapshot : dataSnapshot.getChildren()) {
                Recipe msg = msgSnapshot.getValue(Recipe.class);
                recipes.add(msg);
                Toast.makeText(getApplicationContext(),"LD 
   !!!",Toast.LENGTH_LONG).show();
            }
        }

            @Override
            public void onCancelled (DatabaseError databaseError){
                Toast.makeText(getApplicationContext(),"FAILD 
         !!!",Toast.LENGTH_LONG).show();
            }

    });
   for (int i =0;i<recipes.size();i++){
        t[i] = recipes.get(i).getTitle();
        im[i] = R.drawable.breakfast_1;
    }

    CustomAdapterCategory adapter = new CustomAdapterCategory(this,t,im);
    list.setAdapter(adapter);

  }

}

的build.gradle(APP):

       dependencies {
      compile fileTree(dir: 'libs', include: ['*.jar'])
      compile 'com.android.support:appcompat-v7:25.1.1'
      compile 'com.android.support:design:25.1.1'
      compile 'de.hdodenhof:circleimageview:2.1.0'
      compile 'com.google.firebase:firebase-core:10.2.0'
      compile 'com.google.firebase:firebase-auth:10.2.0'
      compile 'com.google.firebase:firebase-database:10.2.0'
      compile 'com.android.support.constraint:constraint-layout:1.0.2'
      testCompile 'junit:junit:4.12'
     }
     apply plugin: 'com.google.gms.google-services'

1 个答案:

答案 0 :(得分:0)

如果您确定代码没有错误,我想提醒您Firebase连接是异步的。     for (int i =0;i<recipes.size();i++){ t[i] = recipes.get(i).getTitle(); im[i] = R.drawable.breakfast_1; } adapter.notifyDataSetChanged(); 将上面的代码放在onDataChange()的for循环之后。