好吧,大家好,刷新我的适配器有问题,在循环视图中更新项目后,它在firebase中更改但在我的循环视图中没有更改,我必须再次打开活动然后它只显示了解最新信息。
我已经把adapter.notifydatasetchanged()放了,但我认为它不起作用,但在我添加新项目或删除时,它会立即刷新我的回收视图。
private ProgressBar progressBar;
private FirebaseStorage firebaseStorage;
private DatabaseReference databaseReference;
private StorageReference storageReference;
private List<FoodInfo> mfoodinfo;
private ImageView imageView;
private EditText foodname,foodprice,fooddesc,Storename;
SearchView searchView;
ArrayList<FoodInfo> newlist;
private final static int PICK_IMAGE_REQUEST =1;
private Uri imageUri;
private StorageTask mUploadTask;
FoodInfo foodInfo;
ProgressDialog pd;
AlertDialog alertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycleview);
setTitle("Menu");
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
progressBar = findViewById(R.id.progress_circle);
mfoodinfo = new ArrayList<>();
foodAdapter = new FoodAdapter(Recycleview.this, mfoodinfo);
recyclerView.setAdapter(foodAdapter);
Intent intent = getIntent();
String StoreName = intent.getStringExtra("Storename");
foodAdapter.setOnItemClickListener(Recycleview.this);
firebaseStorage = FirebaseStorage.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference("FoodInfo");
pd = new ProgressDialog(this);
pd.setMessage("Updating in Progress");
pd.setCanceledOnTouchOutside(false);
Query query = databaseReference.orderByChild("storename").equalTo(StoreName);
query.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s)
{
mfoodinfo.add(dataSnapshot.getValue(FoodInfo.class));
foodAdapter.setFood(dataSnapshot.getValue(FoodInfo.class));
foodAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void UpdateFood(int position)
{
showUpdateDialog(position);
}
private void showUpdateDialog(int pos) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.update_dialog, null);
dialogBuilder.setView(dialogView);
imageView = (ImageView) dialogView.findViewById(R.id.imageView);
Picasso.with(this).load(mfoodinfo.get(pos).imageUrl).placeholder(R.mipmap.image).resize(150,150).into(imageView);
foodname = (EditText) dialogView.findViewById(R.id.updfood);
foodname.setText(mfoodinfo.get(pos).foodname);
foodprice = (EditText) dialogView.findViewById(R.id.updprice);
foodprice.setText(mfoodinfo.get(pos).foodprice);
fooddesc = (EditText) dialogView.findViewById(R.id.upddesc);
fooddesc.setText(mfoodinfo.get(pos).fooddesc);
Storename = (EditText) dialogView.findViewById(R.id.storename);
Storename.setText(mfoodinfo.get(pos).storename);
final Button update = (Button) dialogView.findViewById(R.id.btnUpdate);
final Button cancel = (Button) dialogView.findViewById(R.id.btnCancel);
dialogBuilder.setTitle("Update");
alertDialog = dialogBuilder.create();
alertDialog.show();
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
UpdateFood(v);
foodAdapter.notifyDataSetChanged();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectImage();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialog.dismiss();
}
});
}
public void selectImage(){
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_PICK);
startActivityForResult(photoPickerIntent, PICK_IMAGE_REQUEST);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
imageUri = data.getData();
Picasso.with(this).load(imageUri).into(imageView);
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
public void UpdateFood(View v) {
final String name = foodname.getText().toString();
foodprice.getText().toString();
fooddesc.getText().toString();
Storename.getText().toString();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
Dialog dialog;
builder.setMessage("Do you want to update this food info?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(final DialogInterface dialog, int which)
{
pd.show();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("FoodInfo").child(name);
final Map m = new HashMap();
m.put("foodprice", foodprice.getText().toString().trim());
m.put("fooddesc", fooddesc.getText().toString().trim());
StorageReference sr = FirebaseStorage.getInstance().getReference();
StorageReference reference = sr.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
reference.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
m.put("imageUrl", taskSnapshot.getDownloadUrl().toString());
databaseReference.updateChildren(m).addOnCompleteListener(new OnCompleteListener<Void>()
{
@Override
public void onComplete(@NonNull Task<Void> task)
{
pd.dismiss();
if(task.isSuccessful())
{
alertDialog.dismiss();
Toast.makeText(Recycleview.this, "Food Updated Successfully", Toast.LENGTH_LONG).show();
foodAdapter.notifyDataSetChanged();
}
else
{
Toast.makeText(Recycleview.this, "Failed to Update" + task.getException(), Toast.LENGTH_LONG).show();
alertDialog.dismiss();
}
}
});
}
}).addOnFailureListener(new OnFailureListener()
{
@Override
public void onFailure(@NonNull Exception e)
{
alertDialog.dismiss();
Toast.makeText(Recycleview.this, "Failed to upload Image" + e.toString(), Toast.LENGTH_SHORT).show();
Log.i("Error Image " , e.toString());
}
});
}
});
builder.setNegativeButton("No", null);
dialog = builder.create();
dialog.show();
}
@Override
public void onItemClick(int position) {
Toast.makeText(this, "Normal click at position: " + position, Toast.LENGTH_SHORT).show();
}
@Override
public void onDeleteClick(final int position)
{
FoodInfo selectedItem;
if(!searchView.getQuery().toString().isEmpty())
{
selectedItem = newlist.get(position);
}
else
{
selectedItem = mfoodinfo.get(position);
}
final String selectedKey = selectedItem.getFoodname();
StorageReference imageRef = firebaseStorage.getReferenceFromUrl(selectedItem.getImageUrl());
imageRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
databaseReference.child(selectedKey).removeValue();
Toast.makeText(Recycleview.this, "Item deleted", Toast.LENGTH_SHORT).show();
mfoodinfo.remove(position);
foodAdapter.notifyDataSetChanged();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
MenuItem menuItem = menu.findItem(R.id.search);
searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(this);
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
newText = newText.toLowerCase();
newlist = new ArrayList<>();
for (FoodInfo foodInfo : mfoodinfo){
String name = foodInfo.getFoodname().toLowerCase();
if (name.contains(newText))
newlist.add(foodInfo);
}
foodAdapter.setFilter(newlist);
return true;
}
}
FoodAdapter.java
private Context mContext;
private List<FoodInfo> mfoodinfo;
private OnItemClickListener mListener;
public FoodAdapter(Context context, List<FoodInfo> mFoodInfo) {
mContext = context;
mfoodinfo = mFoodInfo;
}
@Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.food_inflater, parent, false);
return new ImageViewHolder(v);
}
@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
FoodInfo foodInfo = mfoodinfo.get(position);
holder.tvfood.setText(foodInfo.getFoodname());
holder.tvprice.setText(foodInfo.getFoodprice());
holder.tvdesc.setText(foodInfo.getFooddesc());
Picasso.with(mContext)
.load(foodInfo.getImageUrl())
.placeholder(R.mipmap.ic_launcher)
.fit()
.centerCrop()
.into(holder.imageView);
}
@Override
public int getItemCount() {
return mfoodinfo.size();
}
public void setFilter(List<FoodInfo> newlist) {
mfoodinfo = new ArrayList<>();
mfoodinfo.addAll(newlist);
notifyDataSetChanged();
}
public void setFood(List<FoodInfo> newList) {
this.mfoodinfo = newList;
notifyDataSetChanged();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener{
public TextView tvfood,tvprice,tvdesc;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
tvfood = itemView.findViewById(R.id.tvfoodname);
tvprice = itemView.findViewById(R.id.tvfoodprice);
tvdesc = itemView.findViewById(R.id.tvfooddesc);
imageView = itemView.findViewById(R.id.imageViewfood);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
@Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem delete = menu.add(Menu.NONE, 1, 1, "Delete");
MenuItem update = menu.add(Menu.NONE, 2, 2, "Update ");
update.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
@Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (item.getItemId()) {
case 1:
mListener.onDeleteClick(position);
return true;
case 2:
mListener.UpdateFood(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener {
void onItemClick(int position);
void onDeleteClick(int position);
void UpdateFood(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
答案 0 :(得分:1)
您必须更新FoodAdapter
中的数据集,否则不会更改任何内容。由于您没有发布您的适配器代码,我可以假设它看起来像这样:
foodAdapter.addFood(dataSnapshot.getValue(FoodInfo.class));
以及适配器中的addFood
方法代码:
public void addFood(FoodInfo newFoodInfo) {
mfoodInfo.add(newFoodInfo);
notifyDataSetChanged();
}