与 Gson 的 SharedPreferences 无法正常工作

Posted

技术标签:

【中文标题】与 Gson 的 SharedPreferences 无法正常工作【英文标题】:SharedPreferences with Gson not properly working 【发布时间】:2020-04-14 13:07:58 【问题描述】:

我正在尝试通过 Gson 保存我的 ArrayList 项目 ArrayList<MyItem> items 但是当我重新打开应用程序时,一切都消失了,也没有加载任何数据。

这是我的代码(我正在使用 Fragments)

public class FragmentPage extends Fragment 

private ExampleAdapter mAdapter;
private EditText editTask;
ArrayList<MyItem> items;
private Button insertbtn;
private Button stateButton;
private TextView taskText;
private String task;


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable 
Bundle savedInstanceState) 
    loadData();
    CreateExampleList();


    View view = inflater.inflate(R.layout.page_fragment, container, false);


    RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);
    taskText = view.findViewById(R.id.tv_country);
    insertbtn = view.findViewById(R.id.button_insert);
    editTask = view.findViewById(R.id.editTask);
    stateButton = view.findViewById(R.id.tv_button);

    insertbtn.setEnabled(false);
    editTask.addTextChangedListener(new TextWatcher() 

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) 

        

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) 

            String taskInput = editTask.getText().toString().trim();
            insertbtn.setEnabled(!taskInput.isEmpty());

        

        @Override
        public void afterTextChanged(Editable s) 
            task = editTask.getText().toString().trim();

        
    );


    insertbtn.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            InsertItem();
            SaveData();
            editTask.setText(null);


        
    );


    recyclerView.setHasFixedSize(true);

    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
    new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemViewCacheSize(500);
    mAdapter = new ExampleAdapter(items);
    recyclerView.setAdapter(mAdapter);


    return view;


private void SaveData() 
    SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared 
preferences", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    Gson gson = new Gson();
    String json = gson.toJson(items);
    editor.putString("task list", json);
    editor.apply();


private void loadData() 
    SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared 
preferences", MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sharedPreferences.getString("task list", null);
    Type type = new TypeToken<ArrayList<MyItem>>() 
    .getType();
    items = gson.fromJson(json, type);

    if (items == null) 
        items = new ArrayList();
    



public void InsertItem() 

    items.add(new MyItem(task, stateButton));
    mAdapter.notifyItemInserted(items.size());




private void CreateExampleList() 
    items = new ArrayList<MyItem>();


ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0, 
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) 
    @Override
    public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder 
viewHolder, @NonNull RecyclerView.ViewHolder target) 
        return false;
    

    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) 
        items.remove(viewHolder.getAdapterPosition());
        mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());

    
;

【问题讨论】:

【参考方案1】:

我自己找到了答案。

简直不敢相信……

我只需要在loadData()下方移动View view = inflater.inflate(R.layout.page_fragment, container, false);

【讨论】:

以上是关于与 Gson 的 SharedPreferences 无法正常工作的主要内容,如果未能解决你的问题,请参考以下文章

android----SharedPreference

SharedPreference 返回空颤动

[android] sharedPreference入门

Android中SharedPreference多进程数据共享出错

Dagger 2 不注入 sharedPreference

为什么SharedPreference会引发ANR