无法在Firebase valueEventListener中使用Context

时间:2018-04-27 09:02:14

标签: java android firebase android-context

我正在尝试从Firebase检索项目列表,在检索完所有数据后,我想使用适配器在listView中对数据进行充气。这是我正在使用的代码:

vehicleReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()){

                    for (DataSnapshot data : dataSnapshot.getChildren()){
                        ServiceHistoryDataModel serviceHistoryData = data.getValue(ServiceHistoryDataModel.class);
                        serviceHistoryDataList.add(serviceHistoryData);
                    }

                    ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter (this,serviceHistoryDataList,getLayoutInflater());
                    listView.setAdapter(adapter);

                }else
                    Toast.makeText(ServiceHistoryActivity.this, "No service history available !", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

(请参阅截图)

我收到错误: -

  

ServiceHistoryListAdapter中的ServiceHistoryListAdpter()不能   施加:...“

对于该行:

ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter (this,serviceHistoryDataList,getLayoutInflater());

请您告诉我如何解决这个问题?

enter image description here

5 个答案:

答案 0 :(得分:3)

您想要从匿名类访问封闭类的实例。语法为EnclosingClassName.this。 因此,将行更改为:

ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter(YourActivityName.this,serviceHistoryDataList,getLayoutInflater());

即。在YourActivityName.之前添加this

答案 1 :(得分:2)

只需传递" YourActivityName.this"等参数。你的问题将得到解决。 请查看下面的代码。

ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter(YourActivityName.this,serviceHistoryDataList,getLayoutInflater());

答案 2 :(得分:1)

ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter(YourActivityName.this,serviceHistoryDataList,getLayoutInflater());

答案 3 :(得分:1)

请替换

ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter(this,serviceHistoryDataList,getLayoutInflater());

ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter(YourActivityName.this,serviceHistoryDataList,getLayoutInflater());

答案 4 :(得分:1)

用此替换您的代码。

ServiceHistoryListAdapter adapter = new ServiceHistoryListAdapter(ActivityName.this,serviceHistoryDataList,getLayoutInflater());