Проблема в FirebaseRecyclerAdapter

201
04 июля 2018, 21:10

Проблема в FirebaseRecyclerAdapter. Выдает такую ошибку:

Error:(73, 86) error: constructor FirebaseRecyclerAdapter in class FirebaseRecyclerAdapter cannot be applied to given types; required: FirebaseRecyclerOptions found: Class,int,Class,Query reason: actual and formal argument lists differ in length where T,VH are type-variables: T extends Object declared in class FirebaseRecyclerAdapter VH extends ViewHolder declared in class FirebaseRecyclerAdapter

Уже и документацию читал, и код менял. Ничего не получается. Прошу помощи в решении проблемы. Я новечек у меня не получается это зделать.

private void loadData() {
    Query query = fNotesDatabase.orderByValue();
    FirebaseRecyclerAdapter<NoteModel, NoteViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<NoteModel, NoteViewHolder>(
            NoteModel.class,
            R.layout.activity_notes,
            NoteViewHolder.class,
            query
    ) {
        @Override
        protected void populateViewHolder(final NoteViewHolder viewHolder, NoteModel model, int position) {
            final String noteId = getRef(position).getKey();
            fNotesDatabase.child(noteId).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot.hasChild("title") && dataSnapshot.hasChild("timestamp")) {
                        String title = dataSnapshot.child("title").getValue().toString();
                        String timestamp = dataSnapshot.child("timestamp").getValue().toString();
                        viewHolder.setNoteTitle(title);
                        //viewHolder.setNoteTime(timestamp);
                        GetTimeAgo getTimeAgo = new GetTimeAgo();
                        viewHolder.setNoteTime(getTimeAgo.getTimeAgo(Long.parseLong(timestamp), getApplicationContext()));
                        viewHolder.noteCard.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent(NotesMine.this, NewNoteActivity.class);
                                intent.putExtra("noteId", noteId);
                                startActivity(intent);
                            }
                        });
                    }
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });
        }

Вот изменения в коде.

public class NotesMine extends AppCompatActivity {
private FirebaseAuth fAuth;
private RecyclerView mNotesList;
private GridLayoutManager gridLayoutManager;
private DatabaseReference fNotesDatabase;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    mNotesList = (RecyclerView) findViewById(R.id.notes_list);
    gridLayoutManager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
    mNotesList.setHasFixedSize(true);
    mNotesList.setLayoutManager(gridLayoutManager);
    //  gridLayoutManager.setReverseLayout(true);
    //gridLayoutManager.setStackFromEnd(true);
    mNotesList.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
    fAuth = FirebaseAuth.getInstance();
    if (fAuth.getCurrentUser() != null) {
        fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child(fAuth.getCurrentUser().getUid());
    }
}
@Override
public void onStart() {
    super.onStart();
}

private Query query = fNotesDatabase;
FirebaseRecyclerOptions<NoteModel> options =
        new FirebaseRecyclerOptions.Builder<NoteModel>()
                .setQuery(query, NoteModel.class)
                .build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<NoteModel, NoteViewHolder>(options) {
    @Override
    public NoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.activity_notes, parent, false);
        return new NoteViewHolder(view);
    }
    @Override
    protected void onBindViewHolder(final NoteViewHolder holder, int position, NoteModel model) {
        final String noteId = getRef(position).getKey();
        fNotesDatabase.child(noteId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.hasChild("title") && dataSnapshot.hasChild("timestamp")) {
                    String title = dataSnapshot.child("title").getValue().toString();
                    String timestamp = dataSnapshot.child("timestamp").getValue().toString();
                    holder.setNoteTitle(title);
                    holder.setNoteTime(timestamp);
                    GetTimeAgo getTimeAgo = new GetTimeAgo();
                    holder.setNoteTime(getTimeAgo.getTimeAgo(Long.parseLong(timestamp), getApplicationContext()));
                    holder.noteCard.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(NotesMine.this, NewNoteActivity.class);
                            intent.putExtra("noteId", noteId);
                            startActivity(intent);
                        }
                    });
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
        mNotesList.setAdapter(adapter);
    }
};


private void updateUI() {
    if (fAuth.getCurrentUser() != null){
        Log.i("MainActivity", "fAuth != null");
    } else {
        Intent startIntent = new Intent(NotesMine.this, MainActivity.class);
        startActivity(startIntent);
        finish();
        Log.i("MainActivity", "fAuth == null");
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    switch (item.getItemId()) {
        case R.id.main_new_note_btn:
            Intent newIntent = new Intent(NotesMine.this, NewNoteActivity.class);
            startActivity(newIntent);
            break;
    }
    return true;
}

/**
 * Converting dp to pixel
 */
private int dpToPx(int dp) {
    Resources r = getResources();
    return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}

}

Answer 1

Код должен быть примерно таким:

FirebaseRecyclerOptions<NoteModel> options =
            new FirebaseRecyclerOptions.Builder<NoteModel>()
                    .setQuery(query, NoteModel.class)
                    .build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<NoteModel, NoteViewHolder>(options) {
    @Override
    public NoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.activity_notes, parent, false);
        return new NoteViewHolder(view);
    }
    @Override
    protected void onBindViewHolder(NoteViewHolder holder, int position, NoteModel model) {
        // Сюда перенесете код из populateViewHolder()
        // ...
    }
};
Answer 2

Данный код является правильным для этого типа задач:

public class NotesMine extends AppCompatActivity {
private FirebaseAuth fAuth;
private RecyclerView mNotesList;
private GridLayoutManager gridLayoutManager;
private DatabaseReference fNotesDatabase;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    mNotesList = (RecyclerView) findViewById(R.id.notes_list);
    gridLayoutManager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
    mNotesList.setHasFixedSize(true);
    mNotesList.setLayoutManager(gridLayoutManager);
    mNotesList.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
    fAuth = FirebaseAuth.getInstance();
    if (fAuth.getCurrentUser() != null) {
        fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child(fAuth.getCurrentUser().getUid());
    }
    updateUI();
    loadData();
}
@Override
public void onStart() {
    super.onStart();
}
private  void loadData() {
    Query query = fNotesDatabase;
    FirebaseRecyclerOptions<NoteModel> options =
            new FirebaseRecyclerOptions.Builder<NoteModel>()
                    .setQuery(query, NoteModel.class)
                    .setLifecycleOwner(NotesMine.this)
                    .build();
    final FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<NoteModel, NoteViewHolder>(options) {
        @Override
        public NoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.activity_notes, parent, false);
            return new NoteViewHolder(view);
        }
        @Override
        protected void onBindViewHolder(final NoteViewHolder holder, int position, NoteModel model) {
            final String noteId = getRef(position).getKey();
            fNotesDatabase.child(noteId).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot.hasChild("title") && dataSnapshot.hasChild("timestamp")) {
                        String title = dataSnapshot.child("title").getValue().toString();
                        String timestamp = dataSnapshot.child("timestamp").getValue().toString();
                        holder.setNoteTitle(title);
                        GetTimeAgo getTimeAgo = new GetTimeAgo();
                        holder.setNoteTime(getTimeAgo.getTimeAgo(Long.parseLong(timestamp), getApplicationContext()));
                        holder.noteCard.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent(NotesMine.this, NewNoteActivity.class);
                                intent.putExtra("noteId", noteId);
                                startActivity(intent);
                            }
                        });
                    }
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });
        }
    };
    mNotesList.setAdapter(adapter);
}
private void updateUI() {
    if (fAuth.getCurrentUser() != null){
        Log.i("MainActivity", "fAuth != null");
    } else {
        Intent startIntent = new Intent(NotesMine.this, MainActivity.class);
        startActivity(startIntent);
        finish();
        Log.i("MainActivity", "fAuth == null");
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    switch (item.getItemId()) {
        case R.id.main_new_note_btn:
            Intent newIntent = new Intent(NotesMine.this, NewNoteActivity.class);
            startActivity(newIntent);
            break;
    }
    return true;
}
private int dpToPx(int dp) {
    Resources r = getResources();
    return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
}
READ ALSO
Spring Tutorial почему ошибка?

Spring Tutorial почему ошибка?

Прохожу Spring tutorial этот https://springio/guides/tutorials/bookmarks/

236
Как убить IntentService

Как убить IntentService

Для примера я создал сервис с таймеромТуда передаю какие-то параметры для сверки

133
В каких случаях использовать ThreadLocal context?

В каких случаях использовать ThreadLocal context?

Студия предлагает использовать private final ThreadLocal context = new ThreadLocal(); вместо private Context context; Это может предотвратить утечку памяти?

199