1
基本上從Firebase刪除對象後,notifyDataSetChanged()
不會實時更新它。我試圖從適配器本身刪除對象,但它也失敗。從Firebase中刪除notifyDataSetChanged();不刷新ListView
回到這個片段顯示更新列表,但我認爲這是因爲添加了小孩。這是我的代碼。
public class ArchiveFragment extends Fragment {
public static ArchiveFragment newInstance(Beer beer) {
ArchiveFragment archiveFragment = new ArchiveFragment();
if (beer != null) {
Bundle args = new Bundle();
args.putSerializable("beer", beer);
archiveFragment.setArguments(args);
}
return archiveFragment;
}
public ArchiveFragment(){}
private ArrayList<Beer> beerDB = new ArrayList<>();
private ListView beerList;
private RecyclerView beerRec;
private DatabaseReference mDatabase;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.archive_fragment, container, false);
final Activity activity = getActivity();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
beerList = (ListView)view.findViewById(R.id.beerList);
final ArrayAdapter<Beer> arrayAdapter = new ArrayAdapter<Beer>(getActivity(), android.R.layout.simple_list_item_1,beerDB);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user.getUid()).child("BeerList");
beerList.setAdapter(arrayAdapter);
beerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Object deletedBeer = beerList.getItemAtPosition(i);
Beer delBeer = (Beer) deletedBeer;
deleteBeer(delBeer.getKey());
}
});
mDatabase.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Beer value = dataSnapshot.getValue(Beer.class);
value.setKey(dataSnapshot.getKey());
beerDB.add(value);
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String key = dataSnapshot.getKey();
beerDB.remove(key);
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
return view;
}
public void deleteBeer(String key){
mDatabase.child(key).removeValue();
}
}
它現在正在工作!非常感謝你,我在這幾個小時內與此戰鬥。 :) –
很高興知道這有幫助。 –