我有两个List<>
实例,我清除了两个列表,然后数据丢失了。我使用以下代码清除它:
private List<ContentProfileDashboard> contentListDashboard;
private AdapterProfileDashboard adapterProfileDashboard;
private ContentProfileDashboard contentProfileDashboard;
....
// button in MainFragment not in Adapter
buttonRefresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// this is first list that i clear
contentListDashboard.clear();
// this is second list that i clear from Adapter class List<ContentProfileDashboard> contentList;
adapterProfileDashboard.contentList.clear();
contentListDashboard.add(contentProfileDashboard);
adapterProfileDashboard.notifyDataSetChanged();
}
});
这是MainFragment,名为 ProfileFragment.class
public class ProfileFragment extends Fragment {
//private RecyclerView recyclerSeen;
private RecyclerView recyclerProfileDashboard;
//private List<ContentProfile> contentList;
private List<ContentProfileDashboard> contentListDashboard;
//private AdapterSeenProfileDashboard adapterSeen;
private AdapterProfileDashboard adapterProfileDashboard;
private Boolean isFirstPageFirstLoad = true;
//private ContentProfile contentSeen;
private ContentProfileDashboard contentProfileDashboard;
private Boolean allowRefresh = true;
private CircleImageView profileImage;
private CircleImageView profileStatusImage;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private DocumentSnapshot lastVisible;
private View view;
private TextView profileNickName;
private TextView profileLongName;
private TextView profileStatusIsActive;
private Button buttonRefresh;
private int currentItems, totalItems, scrollOutItems;
private LinearLayoutManager manager;
private Boolean isScrolling = false;
public ProfileFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_profile, container, false);
firebaseAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
//firebaseAuth = FirebaseAuth.getInstance();
Toolbar toolbar = view.findViewById(R.id.toolbarProfile);
// toolbar.setTitle("Rashid");
profileImage = view.findViewById(R.id.circleImageProfile);
profileNickName = view.findViewById(R.id.nick_name);
profileLongName = view.findViewById(R.id.long_name);
profileStatusIsActive = view.findViewById(R.id.status_active);
profileStatusImage = view.findViewById(R.id.circleImageStatus);
profilePosition = view.findViewById(R.id.position_in_company);
//for crate home button
AppCompatActivity activity = (AppCompatActivity) getActivity();
//MainActivity activity = (MainActivity) getActivity(); // MainActivity cannot be cast to android.support.v7.app.ActionBarActivity
if (activity != null) {
activity.setSupportActionBar(toolbar);
if (activity.getSupportActionBar() != null) {
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(false); // back button
activity.getSupportActionBar().setDisplayShowHomeEnabled(true);
activity.getSupportActionBar().setIcon(R.drawable.googleg_disabled_color_18);
activity.getSupportActionBar().setTitle("");
}
}
setHasOptionsMenu(true);
//contentList = new ArrayList<>();
contentListDashboard = new ArrayList<>();
recyclerProfileDashboard = view.findViewById(R.id.recycler_dashboard_profile);
//horizontal
//recyclerSeen = view.findViewById(R.id.recycler_seenBy);
//adapterSeen = new AdapterSeenProfileDashboard(contentList);
adapterProfileDashboard = new AdapterProfileDashboard(contentListDashboard);
//vertical
// recyclerSeen = view.findViewById(R.id.recycler_dashboard_profile);
// recyclerSeen.setLayoutManager(new LinearLayoutManager(container.getContext()));
manager = new LinearLayoutManager(container.getContext());
recyclerProfileDashboard.setLayoutManager(manager);
//horizontal
//recyclerSeen.setLayoutManager(new LinearLayoutManager(container.getContext(), LinearLayoutManager.HORIZONTAL, false));
// vertical
//recyclerSeen.setAdapter(adapterSeen);
recyclerProfileDashboard.setAdapter(adapterProfileDashboard);
profileImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Intent intent = new Intent(getActivity(), Register.class);
// startActivity(intent); // make sr crash from DesignIn not from intent
contentListDashboard.add(contentProfileDashboard);
adapterProfileDashboard.update(contentListDashboard);
}
});
// CHECK 2
buttonRefresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
contentListDashboard.clear();
adapterProfileDashboard.contentList.clear();
contentListDashboard.add(contentProfileDashboard);
adapterProfileDashboard.notifyDataSetChanged();
}
});
// CHECK 2
profileLongName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
adapterProfileDashboard.contentList.clear();
adapterProfileDashboard.contentList.addAll(contentListDashboard);
adapterProfileDashboard.notifyDataSetChanged();
}
});
return view;
}
@Override
public void onStart() {
super.onStart();
loadFirstQuery();
}
public void loadFirstQuery() {
if (firebaseAuth.getCurrentUser() != null) {
contentListDashboard.clear();
String currentUserId = firebaseAuth.getCurrentUser().getUid();
firebaseFirestore
.collection("ProfileDashboard")
.document(currentUserId)
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
if (task.getResult() != null) {
String image = task.getResult().getString("image");
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.ic_profile_off);
Glide.with(Objects.requireNonNull(getActivity())).applyDefaultRequestOptions(requestOptions).load(image).into(profileImage);
String nickName = task.getResult().getString("nickName");
profileNickName.setText(nickName);
String longName = task.getResult().getString("longName");
profileLongName.setText(longName);
String status = task.getResult().getString("status");
if (status != null) {
if (status.equals("ACTIVE")){
profileStatusIsActive.setText(status);
profileStatusImage.setImageResource(R.color.colorAccent);
} else {
profileStatusIsActive.setText(status);
profileStatusImage.setImageResource(R.color.darkGrey);
}
}
String position = task.getResult().getString("position");
profilePosition.setText(position);
}
}
}
});
// recyclerProfileDashboard.addOnScrollListener(new RecyclerView.OnScrollListener() {
// @Override
// public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
// super.onScrolled(recyclerView, dx, dy);
// // horizontal
// //Boolean reachBottom = !recyclerView.canScrollHorizontally(-1);
// // vertical
// Boolean reachBottom = !recyclerView.canScrollVertically(-1);
// if (reachBottom) {
// loadMorePost();
// }
// }
// });
// TRY NEW SCROLL METHOD
recyclerProfileDashboard.addOnScrollListener(new RecyclerView.OnScrollListener(){
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true;
}
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
currentItems = manager.getChildCount();
totalItems = manager.getItemCount();
scrollOutItems = manager.findFirstVisibleItemPosition();
if (isScrolling && (currentItems + scrollOutItems == totalItems)) {
isScrolling = false;
// implement progress bar here
loadMorePost();
}
}
});
// RETRIEVING SEEN
Query firstQuery = firebaseFirestore
.collection("ProfileDashboard")
.document(currentUserId)
.collection("ProfileInfo")
.orderBy("timestamp", Query.Direction.DESCENDING)
.limit(5);
// Activity.this if not fragment /// Objects.requireNonNull(getActivity()),
firstQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (!documentSnapshots.isEmpty()) {
// please add if doc not empty
if (isFirstPageFirstLoad) {
lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1); // array 0, 1, 2
}
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
//String postId = doc.getDocument().getId();
contentProfileDashboard = doc.getDocument().toObject(ContentProfileDashboard.class);
if (isFirstPageFirstLoad) {
contentListDashboard.add(contentProfileDashboard);
} else {
contentListDashboard.add(0, contentProfileDashboard);
}
// fire the event
adapterProfileDashboard.notifyDataSetChanged();
}
}
isFirstPageFirstLoad = false;
}
}
});
}
}
public void loadMorePost() {
if (firebaseAuth.getCurrentUser() != null) {
String currentUserId = firebaseAuth.getCurrentUser().getUid();
Query nextQuery = firebaseFirestore
.collection("ProfileDashboard")
.document(currentUserId)
.collection("ProfileInfo")
.orderBy("timestamp", Query.Direction.DESCENDING)
.startAfter(lastVisible)
.limit(5);
nextQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (!documentSnapshots.isEmpty()) {
lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
//String postId = doc.getDocument().getId();
// contentSeen = doc.getDocument().toObject(ContentProfile.class);
// contentList.add(contentSeen);
contentProfileDashboard = doc.getDocument().toObject(ContentProfileDashboard.class);
contentListDashboard.add(contentProfileDashboard);
//adapterSeen.notifyDataSetChanged();
adapterProfileDashboard.notifyDataSetChanged();
}
}
}
}
});
}
}
这是适配器
public class AdapterProfileDashboard extends RecyclerView.Adapter<AdapterProfileDashboard.ViewHolder> {
public List<ContentProfileDashboard> contentList;
public Context context;
public AdapterProfileDashboard(List<ContentProfileDashboard> contentList){
this.contentList = contentList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_profile_dashboard, parent, false);
context = parent.getContext(); // or add in parameter constructor this.context = context; and set in HomeFragment AdapterFragmentHome(container.getContext(), contentList);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.setIsRecyclable(false);
String text = contentList.get(position).getProfileText();
holder.setUserText(text);
}
@Override
public int getItemCount() {
return contentList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View mView;
private TextView userProfile;
//private TextView textDashboard;
public ViewHolder(View itemView){
super(itemView);
mView = itemView;
}
public void setUserText(String text) {
userProfile = mView.findViewById(R.id.profile_text_dashboard);
userProfile.setText(text);
}
}
}
我的问题是如何正确刷新回收视图?..这样我的数据就不会丢失?