私はRecyclerView
リストのためにCardView
にデータをプッシュするSQLite database
を持っています。私は新しく追加されたCardViews
をリストの先頭に挿入したいが、リストの最後である最後に追加されている。Android RecyclerView:新しいアイテムをリストの一番上に追加するには?
それは、リストの先頭に新しいCardView
を置くべきで尊敬されていないMainActivity
でこのコードのように思える:
contactList.add(0, contact);
私がここで行方不明ですか?
MainActivity.java
@Override
protected void onStart() {
super.onStart();
loadData();
}
void loadData(){
sqLiteDB = new SQLiteDB(this);
List<Contact> contactList = new ArrayList<>();
Cursor cursor = sqLiteDB.retrieve();
Contact contact;
// iterate over the db cursor by using a new cursor for the ArrayList.
try {
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) { // to avoid an infinite loop iteration.
do {
contact = new Contact();
contact.setId(cursor.getInt(0));
contact.setTodo(cursor.getString(1));
**contactList.add(0, contact);** // add the new item to top of R. list.
} while (cursor.moveToNext());
}
}
} finally {
if(cursor !=null && !cursor.isClosed()){
cursor.close();
}
}
contactListAdapter.clear();
contactListAdapter.addAll(contactList);
SQLiteDB.java
public Cursor retrieve(){
SQLiteDatabase db = getReadableDatabase();
String[] projection = {
ContactField.COLUMN_ID,
ContactField.COLUMN_TODO
};
Cursor cursor = db.query(
ContactField.TABLE_NAME,projection,
null,
null,
null,
null,
null
);
if (cursor == null) {
return null;
}
return cursor;
}
ContactListAdapter.java
public class ContactListAdapter extends RecyclerView.Adapter<ContactListAdapter.ContactHolder>{
private List<Contact> contactList;
private Context context;
private RecyclerItemClickListener recyclerItemClickListener;
// Setting to -1 keeps the first CardView (position 0) from having its
// BackGroundColor mistakenly switch from the default to the highlighted/selected
// color which is red.
private int selectedPos = -1;
public ContactListAdapter(Context context) {
this.context = context;
this.contactList = new ArrayList<>();
}
public void clear() {
while (getItemCount() > 0) {
remove(getItem(0));
}
}
public void addAll(List<Contact> contactList) {
for (Contact contact : contactList) {
// add(contact);
contactList.add(0, contact); }
}
// Get the Item's position.
public Contact getItem(int position) {
return contactList.get(position);
}
// Get the Item's Id.
public long getItemId(int position) {
return contactList.get(position).getId();
}
...
あなたの書き込みあなたのaddAll()メソッドを変更内側のdo/whileを削除し、 'cursor.moveToNext()'のままにしてください。また、 'addAll'メソッドの中で連絡先が正しい順序であるかどうかを確認してください。また、アダプタのリストを変更した後に 'contactListAdapter.notifyDataSetChanged()'を呼び出すことも忘れないでください。 – fernandospr
私は内側のdo/whileを削除しようとします。 addAllメソッド内の連絡先が正しい順序であるかどうかを確認するにはどうすればよいですか? – AJW
ブレークポイントを設定してデバッグしたり、各コンタクトを印刷して順番どおりにロードされたかどうかを確認できます。 – fernandospr