# #android #firebase #android-recyclerview #sharedpreferences
Вопрос:
Я хочу реализовать просмотр с несколькими вариантами выбора и сохранить выбранные элементы и их состояние в базе данных телефона либо sqlite, либо sharedpreference(если возможно) и извлечь его в выбранном состоянии. при выборе категории ее фон становится синим, но когда вы возвращаетесь к активности, он остается белым.
Вот мой код
Класс адаптера
public class BlogCategoryAdapter extends RecyclerView.Adapter<BlogCategoryAdapter.BlogCategoryViewHolder> {
List<BlogCategoryModel> blogCategoryModelList;
public BlogCategoryAdapter( List<BlogCategoryModel> blogCategoryModelList) {
this.blogCategoryModelList = blogCategoryModelList;
}
@NonNull
@NotNull
@Override
public BlogCategoryViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_item_layout, parent, false);
return new BlogCategoryViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull @NotNull BlogCategoryViewHolder holder, int position) {
holder.bindBlogCategory(blogCategoryModelList.get(position));
}
@Override
public int getItemCount() {
return blogCategoryModelList.size();
}
public List<BlogCategoryModel> getSelectedBlogCategory(){
List<BlogCategoryModel> selectedBlogCategory = new ArrayList<>();
for (BlogCategoryModel blogCategoryModel : blogCategoryModelList){
if (blogCategoryModel.getSelected()){
selectedBlogCategory.add(blogCategoryModel);
}
}
return selectedBlogCategory;
}
public class BlogCategoryViewHolder extends RecyclerView.ViewHolder{
TextView blogTopic;
public BlogCategoryViewHolder(@NonNull @NotNull View itemView) {
super(itemView);
blogTopic = itemView.findViewById(R.id.category_item_text);
}
// Bind data
void bindBlogCategory(final BlogCategoryModel blogCategoryModel){
blogTopic.setText(blogCategoryModel.getBlogTopic());
blogTopic.setBackgroundResource(blogCategoryModel.getSelected() ?
R.drawable.category_item_selected_bg : R.drawable.category_item_default_bg);
blogTopic.setTextColor(blogCategoryModel.getSelected() ? Color.WHITE : Color.BLACK);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
blogCategoryModel.setSelected(!blogCategoryModel.getSelected());
blogTopic.setBackgroundResource(blogCategoryModel.getSelected() ? R.drawable.category_item_selected_bg : R.drawable.category_item_default_bg);
blogTopic.setTextColor(blogCategoryModel.getSelected() ? Color.WHITE : Color.BLACK);
}
});
}
}
Класс SharedPreference
public class PrefConfig {
private static final String PREFERENCE_NAME = "saved_category";
private static final String PREFERENCE_KEY = "pref_key";
public static void saveSelectedBlogCategoryInPref(Context context, List<BlogCategoryModel> selectedBlogCategory) {
Gson gson = new Gson();
String jsonString = gson.toJson(selectedBlogCategory);
SharedPreferences preferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(PREFERENCE_KEY, jsonString);
editor.apply();
}
public static List<BlogCategoryModel> fetchSelectedBlogCategoryFromPref(Context context) {
SharedPreferences preferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
Gson gson = new Gson();
String jsonString = preferences.getString(PREFERENCE_KEY, null);
Type type = new TypeToken<ArrayList<BlogCategoryModel>>() {}.getType();
return gson.fromJson(jsonString, type);
}
}
Model class
public class BlogCategoryModel implements Serializable {
private String blogTopic;
private Boolean isSelected = false;
public BlogCategoryModel() {
}
public BlogCategoryModel(String blogTopic, Boolean isSelected) {
this.blogTopic = blogTopic;
this.isSelected = isSelected;
}
public String getBlogTopic() {
return blogTopic;
}
public void setBlogTopic(String blogTopic) {
this.blogTopic = blogTopic;
}
public Boolean getSelected() {
return isSelected;
}
public void setSelected(Boolean selected) {
isSelected = selected;
}
}
Активность
public class BlogCategoryActivity extends AppCompatActivity{
List<BlogCategoryModel> blogCategoryModelList;
FloatingActionButton fabSaveCategories;
BlogCategoryAdapter blogCategoryAdapter;
List<BlogCategoryModel> getSelectedDataList;
ListView selectedCategoryListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blog_category);
fabSaveCategories = findViewById(R.id.floatingActionButton);
selectedCategoryListView = findViewById(R.id.selected_category_listview);
getSelectedDataList = PrefConfig.fetchSelectedBlogCategoryFromPref(this);
Log.d("TAG", "getData: " PrefConfig.fetchSelectedBlogCategoryFromPref(this));
if (getSelectedDataList == null) {
getSelectedDataList = new ArrayList<>();
}
ArrayAdapter<BlogCategoryModel> arrayAdapter = new ArrayAdapter<>(this,R.layout.category_item_layout, getSelectedDataList);
selectedCategoryListView.setAdapter(arrayAdapter);
initViews();
getBlogTopic();
fabSaveCategories.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<BlogCategoryModel> selectedBlogCategory = blogCategoryAdapter.getSelectedBlogCategory();
PrefConfig.saveSelectedBlogCategoryInPref(getApplicationContext(), selectedBlogCategory);
Log.d("TAG", "onClick: " selectedBlogCategory);
StringBuilder selectedNames = new StringBuilder();
for (int i = 0; i < selectedBlogCategory.size(); i ) {
selectedNames.append(selectedBlogCategory.get(i).getBlogTopic());
selectedNames.append("n");
}
Toast.makeText(BlogCategoryActivity.this, "" selectedNames.toString().trim(), Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onResume() {
super.onResume();
getSelectedDataList = PrefConfig.fetchSelectedBlogCategoryFromPref(this);
Log.d("TAG", "getData: " PrefConfig.fetchSelectedBlogCategoryFromPref(this));
if (getSelectedDataList == null) {
getSelectedDataList = new ArrayList<>();
}
}
private void getBlogTopic() {
blogCategoryModelList = new ArrayList<>();
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
RecyclerView blogCategoryRecyclerView = findViewById(R.id.blog_category_recyclerview);
blogCategoryRecyclerView.setHasFixedSize(true);
FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(this);
flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);
flexboxLayoutManager.setJustifyContent(JustifyContent.CENTER);
blogCategoryRecyclerView.setLayoutManager(flexboxLayoutManager);
blogCategoryAdapter = new BlogCategoryAdapter(blogCategoryModelList);
blogCategoryRecyclerView.setAdapter(blogCategoryAdapter);
firebaseFirestore.collection("Blog Category")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull @NotNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
blogCategoryModelList.clear();
for (DocumentSnapshot documentSnapshot : task.getResult()){
BlogCategoryModel blogCategoryModel = documentSnapshot.toObject(BlogCategoryModel.class);
blogCategoryModelList.add(blogCategoryModel);
}
blogCategoryAdapter.notifyDataSetChanged();
}
}
});
}
Комментарии:
1. Если вам интересно, вот статья, которая называется » Как удалить несколько записей из Firestore с помощью множественного выбора RecyclerView?». это может помочь.