Как настроить FirebaseAdapter в Android Studio?

Я пытаюсь читать данные в реальном времени из Firebase в пользовательский ArrayAdapter. Судя по моим исследованиям, FirebaseListAdapter имеет встроенную функциональность для решения этой проблемы. Однако я не могу заставить свой код распознавать класс FirebaseListAdapter. Как заставить FirebaseListAdapter работать?

Файл Gradle

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.0"

    defaultConfig {
        applicationId "com.example.quizzingcompanion"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.google.firebase:firebase-database:9.6.0'
    compile 'com.google.firebase:firebase-core:9.6.0'
    compile 'com.google.firebase:firebase-auth:9.6.0'
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'com.android.support:design:24.1.1'
    compile 'com.android.support:support-v4:24.1.1'
    compile 'com.firebase:firebase-client-android:2.3.1'
    compile 'com.firebaseui:firebase-ui:0.6.0'
    compile 'com.firebaseui:firebase-ui-storage:0.6.0'
    compile 'com.firebaseui:firebase-ui-database:0.6.0'
}

apply plugin: 'com.google.gms.google-services'

Инициализация адаптера Firebase

FirebaseListAdapter<Participant> adapter = new FirebaseListAdapter;

Сообщения об ошибках

Failed to resolve: com.google.firebase:firebase-auth:9.6.0
Failed to resolve: com.google.firebase:firebase-storage:9.6.0
Failed to resolve: com.google.firebase:firebase-database:9.6.0
Failed to resolve: com.google.android.gms:play-services-auth:9.6.0
Cannot resolve symbol FirebaseListAdapter

Фрагмент со списком

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class ParticipantFragment extends Fragment {
    private DataSource data;
    DatabaseReference database;
    ArrayList<Participant> participants = new ArrayList<>();

    public ParticipantFragment() {
        data = new DummyDataSource();
        database = FirebaseDatabase.getInstance().getReference();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        final View rootView = inflater.inflate(R.layout.content_participants_fragment, container, false);

        FirebaseListAdapter<Participant> adapter = new FirebaseListAdapter;
        ListView listView = (ListView) rootView.findViewById(R.id.participants_list);
        ParticipantAdapter adapter = new ParticipantAdapter(getActivity(), data.getParticipants());
        listView.setAdapter(adapter);

        FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.participants_fab);
        fab.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), NewParticipant.class);
                startActivity(intent);
            }
        });}

Пользовательский адаптер

import android.app.Activity;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Tim on 9/10/2016.
 */
public class ParticipantAdapter extends ArrayAdapter {
    public ParticipantAdapter(Activity context, ArrayList<Participant> participant) {
        super(context, 0, participant);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View listItemView = convertView;
        if(listItemView == null){
            listItemView = LayoutInflater.from(getContext()).inflate(R.layout.participants_list_item, parent, false);
        }

        Participant currentParticipant = (Participant) getItem(position);

        ImageView participantImage = (ImageView) listItemView.findViewById(R.id.participant_image);
        if(currentParticipant.hasImageValue()){
            participantImage.setImageResource(currentParticipant.getImageID());
        }else{
            participantImage.setImageResource(R.drawable.ic_my_profile);
        }

        TextView name = (TextView) listItemView.findViewById(R.id.participant_name);
        name.setText(currentParticipant.getDisplayName());

        ImageView image = (ImageView) listItemView.findViewById(R.id.participant_role);
        switch (currentParticipant.getRole()){
            case "Official": image.setImageResource(R.drawable.ic_official);
            case "Spectator": image.setImageResource(R.drawable.ic_spectator);
            case "Quizzer": image.setImageResource(R.mipmap.ic_quizzer);
            default: image.setVisibility(View.GONE);
        }

        return listItemView;
    }
}

Где добавляются ценности

Button okBtn = (Button) findViewById(R.id.add_participant);
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View view) {
                DatabaseReference ref = database.child("participants");
                EditText firstName = (EditText)  findViewById(R.id.first_name);
                EditText lastName = (EditText)  findViewById(R.id.last_name);
                Participant newParticipant = new Participant(firstName.getText().toString(),
                                                                lastName.getText().toString(),
                                                                sp.getSelectedItem().toString(),
                                                                sp2.getSelectedItem().toString());
                Map<String, Object> participantValues = newParticipant.toMap();
                ref.push().setValue(participantValues);
            }
        });

person Tim Hutchison    schedule 30.09.2016    source источник
comment
Вы установили последнюю версию сервисов Google Play? Также это руководство может помочь вам inducesmile.com/android/   -  person Inducesmile    schedule 30.09.2016
comment
@NollyJ Да, я только вчера скачал последнюю версию   -  person Tim Hutchison    schedule 30.09.2016


Ответы (2)


FirebaseUI readme содержит этот удобный таблица совместимости:

FirebaseUI  Firebase/Play 
 Version    Services Version
   1.2.0       10.2.0
   1.1.1       10.0.0 or 10.0.1
   1.0.1       10.0.0 or 10.0.1
   1.0.0       9.8.0
   0.6.2       9.8.0
   0.6.1       9.6.1
   0.6.0       9.6.0
   0.5.3       9.4.0
   0.4.4       9.4.0
   0.4.3       9.2.1
   0.4.2       9.2.0
   0.4.1       9.0.2
   0.4.0       9.0.0

Таким образом, чтобы использовать FirebaseUI 0.6, вам придется использовать Firebase/Play Services SDK 9.6. Если вы хотите использовать Firebase/Play Services SDK 9.4, вам придется использовать FirebaseUI 0.5.

Кроме того, вам не хватает оператора импорта для адаптера списка:

import com.firebase.ui.database.FirebaseListAdapter;

Android Studio уже должна давать вам подсказки об этом импорте.

person Frank van Puffelen    schedule 30.09.2016
comment
Это решило проблему с зависимостями, но у меня все еще есть ошибка FragmentListAdapter, а также ошибка с сообщением Не удалось найти поддержку-v4.jar(com.android.support:support-v4:24.1.1) - person Tim Hutchison; 30.09.2016
comment
Это сообщение об ошибке зависит от фактического кода Java. Поскольку вы не предоставили минимальный код, необходимый для воспроизведения ошибки, вам трудно помочь. - person Frank van Puffelen; 30.09.2016
comment
Я добавил еще немного кода в описание — есть ли что-нибудь еще, что вам нужно увидеть? - person Tim Hutchison; 30.09.2016
comment
Я добавил оператор импорта, и импорт выдает ошибку: Cannot Resolve Symbol FirebaseListAdapter - person Tim Hutchison; 03.10.2016

Возможно, вы можете изменить зависимости Firebase на самую новую версию.

compile 'com.google.firebase:firebase-database:9.6.0'
compile 'com.google.firebase:firebase-core:9.6.0'
compile 'com.google.firebase:firebase-auth:9.6.0'
person Jean.lai    schedule 30.09.2016