将 Arryaylist 作为共享首选项保存到 json 后,在 Fragment 中实现 RecyclerView 时遇到问题

问题描述 投票:0回答:1

我无法显示片段,但我的活动中没有显示任何内容。我的目标是将sharedpreference保存为gson,因为arraylist无法保存到sharedpreference中,然后使用gson在recyclerview中以片段形式显示arraylist

这是我的活动,它将用户输入数据保存到 json

private void saveDataToSharedPreference(String categoryId, String categoryName, Integer eventCount, Boolean switchActivated){
    ArrayList<CategoryList> category_list = new ArrayList<CategoryList>();
    SharedPreferences preferences = getSharedPreferences("CategoryInfo",MODE_PRIVATE);

    SharedPreferences.Editor edit = getPreferences(MODE_PRIVATE).edit();
    category_list.add(new CategoryList(categoryId,categoryName,eventCount,switchActivated));
    String json = gson.toJson(category_list);

    edit.putString("category_info",json);
    edit.apply();
}

这是我显示回收器视图的片段


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FragmentListCategory#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragmentListCategory extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    ArrayList<CategoryList> listCategory = new ArrayList<>();
    RecyclerView myRecyclerView;
    RecyclerView.LayoutManager layoutManager;
    MyRecyclerAdapter recyclerAdapter;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public FragmentListCategory() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CategoryListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FragmentListCategory newInstance(String param1, String param2) {
        FragmentListCategory fragment = new FragmentListCategory();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_list_category, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        myRecyclerView = view.findViewById(R.id.categoryRecyclerView);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        layoutManager = new LinearLayoutManager(getView().getContext());
        myRecyclerView.setLayoutManager(layoutManager);
        MyRecyclerAdapter myRecyclerAdapter = new MyRecyclerAdapter(getContext(),listCategory);
        myRecyclerView.setAdapter(myRecyclerAdapter);
        myRecyclerAdapter.notifyDataSetChanged();

    }


这是我的回收适配器

public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.CustomViewHolder>{

    Context context;
    ArrayList<CategoryList> categoryArrayList = new ArrayList<CategoryList>();

    public MyRecyclerAdapter(Context context,ArrayList<CategoryList> categoryArrayList){
        this.context = context;
        this.categoryArrayList = categoryArrayList;
    }


    @NonNull
    @Override
    public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_card_layout, parent, false);
        return new CustomViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
        holder.tvCategoryId.setText(categoryArrayList.get(position).getCat_id());
        holder.tvCategoryName.setText(categoryArrayList.get(position).getCat_name());
        holder.tvEventCount.setText(String.valueOf(categoryArrayList.get(position).getEvent_count()));
        if (categoryArrayList.get(position).getIs_active()){
            holder.tvIsActive.setText("Yes");
        } else {
            holder.tvIsActive.setText("No");
        }
    }

    @Override
    public int getItemCount() {
        return categoryArrayList.size();
    }

    public static class CustomViewHolder extends RecyclerView.ViewHolder {

        public TextView tvCategoryId;
        public TextView tvCategoryName;
        public TextView tvEventCount;
        public TextView tvIsActive;

        public CustomViewHolder(@NonNull View itemView) {
            super(itemView);
            tvCategoryId = itemView.findViewById(R.id.tv_id);
            tvCategoryName = itemView.findViewById(R.id.tv_name);
            tvEventCount = itemView.findViewById(R.id.tv_eventcount);
            tvIsActive = itemView.findViewById(R.id.tv_active);
        }
    }
}

我记录了 json 文件并正确保存,如下所示: [{“cat_id”:“CFO-6328”,“cat_name”:“你好”,“event_count”:231,“is_active”:false}] 在 logcat 所以我很困惑我应该做什么才能让片段显示在我的活动中

android android-fragments android-recyclerview mobile-application mobile-development
1个回答
0
投票

您需要创建一个函数

fun getDataFromSharedPrefs(): List<CategoryList> {
    SharedPreferences prefs = this.getSharedPreferences("CategoryInfo", Context.MODE_PRIVATE);
    String json = prefs.getString("category_info", null);
    //parse to List<CategoryList> and return
    
}

然后在 onViewCreated 内的片段中

 @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        listCategory = getDataFromSharedPreferences(); //add this line
        myRecyclerView = view.findViewById(R.id.categoryRecyclerView);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        layoutManager = new LinearLayoutManager(getView().getContext());
        myRecyclerView.setLayoutManager(layoutManager);
        MyRecyclerAdapter myRecyclerAdapter = new MyRecyclerAdapter(getContext(),listCategory);
        myRecyclerView.setAdapter(myRecyclerAdapter);
        myRecyclerAdapter.notifyDataSetChanged();

    }
© www.soinside.com 2019 - 2024. All rights reserved.