Room печатает только первую строку

#android #android-recyclerview #android-room

#Android #android-recyclerview #android-room

Вопрос:

Я пишу простое приложение, которое хранит 2 строковых значения в базе данных, используя Room (я пытаюсь изучить эту библиотеку). Итак, в моем списке есть только одна строка. Представлено впервые. Остальные не отображаются. В чем причина такого поведения?

Модель

 @Entity
public class Note {

    @PrimaryKey(autoGenerate = true)
    private long id;
    private String title;
    private String text;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}
  

NoteDao

 @Dao
public interface NoteDao {

    @Insert
    void insert(Note note);

    @Delete
    void delete(Note note);

    @Query("SELECT * FROM Note")
    List<Note> getAllNotes();

}
  

AppDatabase

 @Database(entities = Note.class, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract NoteDao getNoteDao();
}
  

DataManager

 public class DataManager {

    private AppDatabase appDatabase;

    public DataManager (AppDatabase appDatabase) {
        this.appDatabase = appDatabase;
    }

    public List <Note> getNotes () {
        try {
            return new GetNotes (). execute (). get ();
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace ();
            return null;
        }
    }

    public void insertNote (Note note) {
        new InsertNote (note) .execute ();
    }

    public void deleteNote (Note note) {
        new DeleteNote (note) .execute ();
    }


    // Get all notes
    public class GetNotes extends AsyncTask <Void, Void, List <Note>> {

        @Override
        protected List <Note> doInBackground (Void ... voids) {
            return appDatabase.getNoteDao (). getAllNotes ();
        }
    }

    // Insert note
    public class InsertNote extends AsyncTask <Void, Void, Void> {

        private Note note;

        InsertNote (Note note) {
            this.note = note;
        }

        @Override
        protected Void doInBackground (Void ... voids) {
            appDatabase.getNoteDao (). insert (note);
            return null;
        }
    }

    // Delete note
    public class DeleteNote extends AsyncTask <Void, Void, Void> {

        private Note note;

        public DeleteNote (Note note) {
            this.note = note;
        }

        @Override
        protected Void doInBackground (Void ... voids) {
            appDatabase.getNoteDao (). delete (note);
            return null;
        }
    }
}
  

Mvp

 public interface NoteListView extends MvpView {
    void showNoteList(List<Note> note);
}
  

Presenter

 public class NoteListPresenter extends MvpPresenter<NoteListView> {

    private DataManager dataManager;

    public NoteListPresenter(DataManager dataManager) {
        this.dataManager = dataManager;
    }

    public void getNotes(){
        getView().showNoteList(dataManager.getNotes());
    }

    public void deleteNote(Note note) {
        dataManager.deleteNote(note);
        getView().showNoteList(dataManager.getNotes());
    }
}
  

Adapter

 public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.ViewHolder> {

    private List<Note> listNote;
    private Context context;

    public NoteAdapter(Context context, List<Note> listNote) {
        this.listNote = listNote;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.title.setText(listNote.get(position).getTitle());
        holder.text.setText(listNote.get(position).getText());
    }

    @Override
    public int getItemCount() {
        return listNote.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView title, text;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
            text = itemView.findViewById(R.id.text);
        }
    }
}
  

MainActivity

 public class MainActivity extends AppCompatActivity implements NoteListView {

    private NoteListPresenter presenter;
    private RecyclerView recyclerView;
    private NoteAdapter noteAdapter;
    private ConstraintLayout constraintLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        constraintLayout = findViewById(R.id.coordinatorMain);

        recyclerView = findViewById(R.id.recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        presenter = new NoteListPresenter(App.getDataManager());
        presenter.attachView(this);
        presenter.getNotes();
    }

    public void onNextActivity(View view){
        startActivity(new Intent(MainActivity.this, AddNoteActivity.class));
    }

    @Override
    public void showNoteList(List<Note> note) {
        noteAdapter = new NoteAdapter(this, note);
        recyclerView.setAdapter(noteAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.getNotes();
    }

    @Override
    public void showMessage(String message) {
        Snackbar.make(constraintLayout, message, Snackbar.LENGTH_SHORT).show();
    }
}
  

UPD

SaveNoteView

 public interface SaveNoteView extends MvpView {
    void insertNote(Note note);
}
  

SaveNotePresenter

 public class SaveNotePresenter extends MvpPresenter<SaveNoteView> {

    private DataManager dataManager;

    public SaveNotePresenter(DataManager dataManager) {
        this.dataManager = dataManager;
    }

    public void insertNote(Note note){
        dataManager.insertNote(note);
        getView().insertNote(note);
    }
}
  

AddNoteActivity

 public class AddNoteActivity extends AppCompatActivity implements SaveNoteView {

    private TextInputEditText title, text;
    private ConstraintLayout constraintLayout;
    private SaveNotePresenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_note);

        constraintLayout = findViewById(R.id.constrainAdd);

        title = findViewById(R.id.titleEditText);
        text = findViewById(R.id.textEditText);

        presenter = new SaveNotePresenter(App.getDataManager());
        presenter.attachView(this);
    }

    //Save a note
    public void saveNote(View view){

        Note note = new Note();
        note.setTitle(title.getText().toString());
        note.setText(text.getText().toString());

        presenter.insertNote(note);
        finish();
    }

    @Override
    public void insertNote(Note note) {
        DataManager dataManager = App.getDataManager();
        dataManager.insertNote(note);
    }

    @Override
    public void showMessage(String message) {
        Snackbar.make(constraintLayout, message, Snackbar.LENGTH_SHORT).show();
    }
}
  

Комментарии:

1. Где вызывается insertNote?

2. добавлен @MerthanE

Ответ №1:

Вполне вероятно, что существует только 1 идентификатор, который постоянно заменяется (если это не так, проверьте, как часто выполняется вставка)

Я использовал Kotlin с Room, но в этом официальном примере у них есть общедоступный автоматически сгенерированный PrimaryKey, который может потребоваться Room для доступа к нему и его автоматической генерации. Поэтому сделайте переменную общедоступной и посмотрите, работает ли она

Ответ №2:

Проблем не было. Я только что указал родительский макет для item_list в полноэкранном режиме. Следовательно, последующие не были видны. Глупая ошибка: D