更改 Text 后在 SharedPrefences 中保存 EditText 的值

Saving value of EditText in SharedPrefences after Text is changed

我试图在更改后自动保存我的 EditText topic 的数据,但我得到的是这个 logcat

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference at com.example.barryblack.FragmentPage0.onCreateView(FragmentPage0.java:68)

这是问题所在的代码

final SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this.getActivity());

    topic = view.findViewById(R.id.topicText0);

    topic.setText(prefs.getString("autosave", ""));
    topic.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) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            prefs.edit().putString("autosave", s.toString()).apply();

        }
    });

如果需要,这是我的全部代码(loadData()SaveDate() 是我用来保存 ArarayList 的方法,但与我的问题无关)

package com.example.barryblack;



public class FragmentPage0 extends Fragment {

private ExampleAdapter mAdapter;
private EditText editTask;
private Button insertbtn;
private TextView taskText;

private String task;


Context context;
ArrayList<MyItem> items;


private static final String SHARED_PREFS_FRAGMENT_A = "fragmentA";

private EditText topic;


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


    CreateExampleList();


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




    loadData();

    final SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this.getActivity());

    topic = view.findViewById(R.id.topicText0);

    topic.setText(prefs.getString("autosave", ""));
    topic.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) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            prefs.edit().putString("autosave", s.toString()).apply();

        }
    });




    RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);
    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);


    taskText = view.findViewById(R.id.tv_country);
    insertbtn = view.findViewById(R.id.button_insert);
    editTask = view.findViewById(R.id.editTask);


    context = getActivity();


    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);


        }
    });


    return view;
}


private void SaveData() {
    SharedPreferences sharedPreferences = 
this.getActivity().getSharedPreferences(SHARED_PREFS_FRAGMENT_A, 
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_PREFS_FRAGMENT_A, 
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));
    mAdapter.notifyItemInserted(items.size());
    SaveData();


}

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());
        SaveData();

    }
};

}

当您引用 topic 时,变量尚未实例化。

你必须在 topic.setText(prefs.getString("autosave", "")) 之前加上 topic = view.findViewById(R.id.topicText0)

编辑:将 onViewCreated 方法添加到片段并将所有代码从 onCreateView 移动到 onViewCreated,如下所示:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.page_fragment1, container, false);
}

public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // move your code here
    topic = view.findViewById(R.id.topicText0);
    // etc.
}

主题 未初始化。 先初始化变量

topic = view.findViewById(R.id.topicText0);

然后设置要查看的文字

topic.setText(prefs.getString("autosave", ""));

然后添加更改侦听器

topic.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) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            prefs.edit().putString("autosave", s.toString()).apply();

        }
    });

放这些:

topic.setText(prefs.getString("autosave", ""));
topic.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) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        prefs.edit().putString("autosave", s.toString()).apply();

    }
});

在这一行的正下方:

topic = view.findViewById(R.id.topicText0);