回收站视图未使用 notifyDataSetChanged() 进行更新;
Recycler view not updating with notifyDataSetChanged();
当我关闭对话框时,它不会使用新数据刷新其下方的 activity。我需要手动刷新 activity 或启动一个新的 activity(看起来很老套)才能显示,我不确定为什么我的 recyclerViewAdapter.notifyDataSetChanged();在 saveItem 方法中不起作用。
package com.bawp.babyneeds;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.bawp.babyneeds.data.DatabaseHandlerDiary;
import com.bawp.babyneeds.model.Diary;
import com.bawp.babyneeds.ui.RecyclerViewAdapter;
import java.util.ArrayList;
import java.util.List;
public class ListActivity extends AppCompatActivity {
private static final String TAG = "ListActivity";
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
private List<Diary> diaryList;
private DatabaseHandlerDiary databaseHandlerDiary;
private FloatingActionButton fab;
private AlertDialog.Builder builder;
private AlertDialog alertDialog;
private Button saveButton;
private EditText diaryName;
private EditText diaryDesc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
recyclerView = findViewById(R.id.recyclerview);
fab = findViewById(R.id.fab);
databaseHandlerDiary = new DatabaseHandlerDiary(this);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
diaryList = new ArrayList<>();
//Get items from db
diaryList = databaseHandlerDiary.getAllDiaries();
for (Diary diary : diaryList) {
Log.d(TAG, "onCreate: " + diary.getDiaryDesc());
}
recyclerViewAdapter = new RecyclerViewAdapter(this, diaryList);
recyclerView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.notifyDataSetChanged();
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createPopDialog();
}
});
}
private void createPopDialog() {
builder = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.popup, null);
diaryName = view.findViewById(R.id.edit_text_name_diary);
diaryDesc = view.findViewById(R.id.edit_text_desc_diary);
saveButton = view.findViewById(R.id.saveButton);
builder.setView(view);
alertDialog = builder.create();
alertDialog.show();
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!diaryName.getText().toString().isEmpty()
&& !diaryDesc.getText().toString().isEmpty()) {
saveItem(v);
//recyclerViewAdapter.notifyDataSetChanged();
}else {
Snackbar.make(v, "Empty Fields not Allowed", Snackbar.LENGTH_SHORT)
.show();
}
}
});
}
private void saveItem(View view) {
//Todo: save each baby diary to db
final Diary diary = new Diary();
String newDiary = diaryName.getText().toString().trim();
String newDesc = diaryDesc.getText().toString().trim();
diary.setDiaryName(newDiary);
diary.setDiaryDesc(newDesc);
databaseHandlerDiary.addDiary(diary);
recyclerViewAdapter.notifyDataSetChanged(); // <-------------------------this is not working
Snackbar.make(view, "Diary Saved",Snackbar.LENGTH_SHORT)
.show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
alertDialog.dismiss();
//Todo: move to next screen - details screen
//startActivity(new Intent(ListActivity.this, ListActivity.class));
//finish();
}
}, 1000);
}
}
谢谢...
已添加 DatabaseHandlerDiary class
package com.bawp.babyneeds.data;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.bawp.babyneeds.model.Diary;
import com.bawp.babyneeds.R;
import com.bawp.babyneeds.util.Util;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class DatabaseHandlerDiary extends SQLiteOpenHelper {
public DatabaseHandlerDiary(Context context) {
super(context, Util.DATABASE_NAME_DIARY, null, Util.DATA_BASE_VERSION_DIARY);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DIARY_TABLE = "CREATE TABLE " + Util.TABLE_NAME_DIARY + " ("
+ Util.KEY_ID_DIARY + " INTEGER PRIMARY KEY," + Util.KEY_NAME_DIARY + " TEXT,"
+ Util.KEY_DESC_DIARY + " TEXT," + Util.KEY_DATE_ADDED_DIARY + ")";
db.execSQL(CREATE_DIARY_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String DROP_TABLE = String.valueOf(R.string.db_drop);
db.execSQL(DROP_TABLE, new String[]{Util.DATABASE_NAME_DIARY});
//create new table
onCreate(db);
}
//CRUD: create read update delete
//add diary
public void addDiary(Diary diary) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Util.KEY_NAME_DIARY, diary.getDiaryName());
values.put(Util.KEY_DESC_DIARY, diary.getDiaryDesc());
values.put(Util.KEY_DATE_ADDED_DIARY, diary.getDateDiaryAdded());
//^ insert to row
db.insert(Util.TABLE_NAME_DIARY, null, values);
db.close();
}
//get diary
public Diary getDiary(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Util.TABLE_NAME_DIARY, new String[]{
Util.KEY_NAME_DIARY, Util.KEY_DESC_DIARY, Util.KEY_DATE_ADDED_DIARY},
Util.KEY_ID_DIARY +"=?", new String[]{String.valueOf(id)},
null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
Diary diary = new Diary();
diary.setDiaryId(Integer.parseInt(cursor.getString(0)));
diary.setDiaryName(cursor.getString(1));
diary.setDiaryDesc(cursor.getString(2));
return diary;
}
//get all diaries
public List<Diary> getAllDiaries() {
SQLiteDatabase db = this.getReadableDatabase();
List<Diary> diaryList = new ArrayList<>();
Cursor cursor = db.query(Util.TABLE_NAME_DIARY,
new String[]{Util.KEY_ID_DIARY,
Util.KEY_NAME_DIARY,
Util.KEY_DESC_DIARY,
Util.KEY_DATE_ADDED_DIARY},
null, null, null, null,
Util.KEY_DATE_ADDED_DIARY + " DESC");
if (cursor.moveToFirst()) {
do {
Diary diary = new Diary();
diary.setDiaryId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Util.KEY_ID_DIARY))));
diary.setDiaryName(cursor.getString(cursor.getColumnIndex(Util.KEY_NAME_DIARY)));
diary.setDiaryDesc(cursor.getString(cursor.getColumnIndex(Util.KEY_DESC_DIARY)));
//convert Timestamp to something readable
DateFormat dateFormat = DateFormat.getDateInstance();
String formattedDate = dateFormat.format(new Date(cursor.getLong(cursor.getColumnIndex(Util.KEY_DATE_ADDED_DIARY)))
.getTime()); // Feb 23, 2020
diary.setDateDiaryAdded(formattedDate);
//Add to arraylist
diaryList.add(diary);
} while (cursor.moveToNext());
}
return diaryList;
}
public int updateItem(Diary diary) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Util.KEY_NAME_DIARY, diary.getDiaryName());
values.put(Util.KEY_DESC_DIARY, diary.getDiaryDesc());
values.put(Util.KEY_DATE_ADDED_DIARY, java.lang.System.currentTimeMillis());//timestamp of the system
//update row
return db.update(Util.TABLE_NAME_DIARY, values,
Util.KEY_ID_DIARY + "=?",
new String[]{String.valueOf(diary.getDiaryId())});
}
//Todo: Add Delete Item
public void deleteItem(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Util.TABLE_NAME_DIARY,
Util.KEY_ID_DIARY + "=?",
new String[]{String.valueOf(id)});
//close
db.close();
}
//Todo: getItemCount
public int getItemsCount() {
String countQuery = "SELECT * FROM " + Util.TABLE_NAME_DIARY;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
return cursor.getCount();
}
}
将 diary
添加到 diaryList
,然后通知您的适配器
diaryList.add(diary);
recyclerViewAdapter.notifyDataSetChanged();
为了使其更优化,请调用
recyclerViewAdapter.notifyItemInserted(diaryList.size() - 1)
您不需要更新所有数据集,您只需要通知添加的项目
当我关闭对话框时,它不会使用新数据刷新其下方的 activity。我需要手动刷新 activity 或启动一个新的 activity(看起来很老套)才能显示,我不确定为什么我的 recyclerViewAdapter.notifyDataSetChanged();在 saveItem 方法中不起作用。
package com.bawp.babyneeds;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.bawp.babyneeds.data.DatabaseHandlerDiary;
import com.bawp.babyneeds.model.Diary;
import com.bawp.babyneeds.ui.RecyclerViewAdapter;
import java.util.ArrayList;
import java.util.List;
public class ListActivity extends AppCompatActivity {
private static final String TAG = "ListActivity";
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
private List<Diary> diaryList;
private DatabaseHandlerDiary databaseHandlerDiary;
private FloatingActionButton fab;
private AlertDialog.Builder builder;
private AlertDialog alertDialog;
private Button saveButton;
private EditText diaryName;
private EditText diaryDesc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
recyclerView = findViewById(R.id.recyclerview);
fab = findViewById(R.id.fab);
databaseHandlerDiary = new DatabaseHandlerDiary(this);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
diaryList = new ArrayList<>();
//Get items from db
diaryList = databaseHandlerDiary.getAllDiaries();
for (Diary diary : diaryList) {
Log.d(TAG, "onCreate: " + diary.getDiaryDesc());
}
recyclerViewAdapter = new RecyclerViewAdapter(this, diaryList);
recyclerView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.notifyDataSetChanged();
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createPopDialog();
}
});
}
private void createPopDialog() {
builder = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.popup, null);
diaryName = view.findViewById(R.id.edit_text_name_diary);
diaryDesc = view.findViewById(R.id.edit_text_desc_diary);
saveButton = view.findViewById(R.id.saveButton);
builder.setView(view);
alertDialog = builder.create();
alertDialog.show();
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!diaryName.getText().toString().isEmpty()
&& !diaryDesc.getText().toString().isEmpty()) {
saveItem(v);
//recyclerViewAdapter.notifyDataSetChanged();
}else {
Snackbar.make(v, "Empty Fields not Allowed", Snackbar.LENGTH_SHORT)
.show();
}
}
});
}
private void saveItem(View view) {
//Todo: save each baby diary to db
final Diary diary = new Diary();
String newDiary = diaryName.getText().toString().trim();
String newDesc = diaryDesc.getText().toString().trim();
diary.setDiaryName(newDiary);
diary.setDiaryDesc(newDesc);
databaseHandlerDiary.addDiary(diary);
recyclerViewAdapter.notifyDataSetChanged(); // <-------------------------this is not working
Snackbar.make(view, "Diary Saved",Snackbar.LENGTH_SHORT)
.show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
alertDialog.dismiss();
//Todo: move to next screen - details screen
//startActivity(new Intent(ListActivity.this, ListActivity.class));
//finish();
}
}, 1000);
}
}
谢谢...
已添加 DatabaseHandlerDiary class
package com.bawp.babyneeds.data;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.bawp.babyneeds.model.Diary;
import com.bawp.babyneeds.R;
import com.bawp.babyneeds.util.Util;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class DatabaseHandlerDiary extends SQLiteOpenHelper {
public DatabaseHandlerDiary(Context context) {
super(context, Util.DATABASE_NAME_DIARY, null, Util.DATA_BASE_VERSION_DIARY);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DIARY_TABLE = "CREATE TABLE " + Util.TABLE_NAME_DIARY + " ("
+ Util.KEY_ID_DIARY + " INTEGER PRIMARY KEY," + Util.KEY_NAME_DIARY + " TEXT,"
+ Util.KEY_DESC_DIARY + " TEXT," + Util.KEY_DATE_ADDED_DIARY + ")";
db.execSQL(CREATE_DIARY_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String DROP_TABLE = String.valueOf(R.string.db_drop);
db.execSQL(DROP_TABLE, new String[]{Util.DATABASE_NAME_DIARY});
//create new table
onCreate(db);
}
//CRUD: create read update delete
//add diary
public void addDiary(Diary diary) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Util.KEY_NAME_DIARY, diary.getDiaryName());
values.put(Util.KEY_DESC_DIARY, diary.getDiaryDesc());
values.put(Util.KEY_DATE_ADDED_DIARY, diary.getDateDiaryAdded());
//^ insert to row
db.insert(Util.TABLE_NAME_DIARY, null, values);
db.close();
}
//get diary
public Diary getDiary(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Util.TABLE_NAME_DIARY, new String[]{
Util.KEY_NAME_DIARY, Util.KEY_DESC_DIARY, Util.KEY_DATE_ADDED_DIARY},
Util.KEY_ID_DIARY +"=?", new String[]{String.valueOf(id)},
null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
Diary diary = new Diary();
diary.setDiaryId(Integer.parseInt(cursor.getString(0)));
diary.setDiaryName(cursor.getString(1));
diary.setDiaryDesc(cursor.getString(2));
return diary;
}
//get all diaries
public List<Diary> getAllDiaries() {
SQLiteDatabase db = this.getReadableDatabase();
List<Diary> diaryList = new ArrayList<>();
Cursor cursor = db.query(Util.TABLE_NAME_DIARY,
new String[]{Util.KEY_ID_DIARY,
Util.KEY_NAME_DIARY,
Util.KEY_DESC_DIARY,
Util.KEY_DATE_ADDED_DIARY},
null, null, null, null,
Util.KEY_DATE_ADDED_DIARY + " DESC");
if (cursor.moveToFirst()) {
do {
Diary diary = new Diary();
diary.setDiaryId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Util.KEY_ID_DIARY))));
diary.setDiaryName(cursor.getString(cursor.getColumnIndex(Util.KEY_NAME_DIARY)));
diary.setDiaryDesc(cursor.getString(cursor.getColumnIndex(Util.KEY_DESC_DIARY)));
//convert Timestamp to something readable
DateFormat dateFormat = DateFormat.getDateInstance();
String formattedDate = dateFormat.format(new Date(cursor.getLong(cursor.getColumnIndex(Util.KEY_DATE_ADDED_DIARY)))
.getTime()); // Feb 23, 2020
diary.setDateDiaryAdded(formattedDate);
//Add to arraylist
diaryList.add(diary);
} while (cursor.moveToNext());
}
return diaryList;
}
public int updateItem(Diary diary) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Util.KEY_NAME_DIARY, diary.getDiaryName());
values.put(Util.KEY_DESC_DIARY, diary.getDiaryDesc());
values.put(Util.KEY_DATE_ADDED_DIARY, java.lang.System.currentTimeMillis());//timestamp of the system
//update row
return db.update(Util.TABLE_NAME_DIARY, values,
Util.KEY_ID_DIARY + "=?",
new String[]{String.valueOf(diary.getDiaryId())});
}
//Todo: Add Delete Item
public void deleteItem(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Util.TABLE_NAME_DIARY,
Util.KEY_ID_DIARY + "=?",
new String[]{String.valueOf(id)});
//close
db.close();
}
//Todo: getItemCount
public int getItemsCount() {
String countQuery = "SELECT * FROM " + Util.TABLE_NAME_DIARY;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
return cursor.getCount();
}
}
将 diary
添加到 diaryList
,然后通知您的适配器
diaryList.add(diary);
recyclerViewAdapter.notifyDataSetChanged();
为了使其更优化,请调用
recyclerViewAdapter.notifyItemInserted(diaryList.size() - 1)
您不需要更新所有数据集,您只需要通知添加的项目