片段之间的共享首选项不起作用

Doesn't work sharedpreferences between fragments

我有两个片段。在第一个片段中,我输入文本,然后通过 sharedPreferences 将此文本传递给第二个片段。第二个片段显示但没有文本。调试时,我看到方法 loadText() 中的第二个片段是 null.But 我不知道如何修复此错误。 UPD:在 editor.putString("saved_text", savedApiKey); 中,如果我输入字符串值(例如 "hello word" 而不是 savedApiKey 它效果很好。 第一个片段:

public class FirstFragment extends Fragment {
    private TextView textInFragment;
    private EditText enteredApiKey;
    private Button button;
    private SharedPreferences sharedPreferences;
    private static final String APP_PREFERENCES = "myPreferences";
    private String savedApiKey;

    public FirstFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.first_fragment, container, false);

        textInFragment = view.findViewById(R.id.textInFirstFragment);
        enteredApiKey = view.findViewById(R.id.enteredApiKey);
        button = view.findViewById(R.id.button);
        savedApiKey = enteredApiKey.getText().toString();
        saveText(savedApiKey);

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SourceFragment newFragment = new SourceFragment();
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, newFragment).addToBackStack(null).commit();
            }
        });
        return view;
    }
  private void saveText(String savedApiKey) {
        sharedPreferences = getContext().getSharedPreferences(APP_PREFERENCES,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("saved_text", savedApiKey);
        editor.commit();
             }}

和第二个片段:

public class SourceFragment extends Fragment  {
    private RecyclerView recyclerView;
    private SharedPreferences sharedPreferences;
    public static final String APP_PREFERENCES = "myPreferences";
    private String API_KEY;

    public SourceFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.source_fragment, container, false);
        TextView text = view.findViewById(R.id.text);
        text.setText(loadText());
        return view;
    }

    private String loadText() {
        sharedPreferences =getContext().getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
        API_KEY = sharedPreferences.getString("saved_text", null);
        return API_KEY;
    }
}

当我在 onPause() 方法中调用 saveText() 方法时,如:

@Override
    public void onPause() {
        super.onPause();
        savedApiKey = enteredApiKey.getText().toString();
        saveText();
    }

有效

onCreateView 调用时,editText 中没有文本。您应该在输入后调用 saveText()。例如在按钮的 onClickListener().

但最好在片段之间使用参数来传输数据。

使用捆绑包。这是一个例子:

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

然后在您的 Fragment 中检索数据(例如在 onCreate() 方法中):

Bundle bundle = this.getArguments();
if (bundle != null) {
    int myInt = bundle.getInt(key, defaultValue);
}

并且不要像这样使用共享首选项。 实际上使用名称为 SharedPreference 的 Class 并使其成为单例并在任何你想要的地方使用它而没有任何问题。 示例代码:

public class NameSP {
       private static NameSP spInstance = null;
       private Stirng Text;
       public static NameSP getSPInstance(){
       if (spInstance == null)
           spInstance = new NameSP();
       return spInstance;
       }
       
       public void saveInfo(){
           SharedPreferences sp = 
                  context.getSharedPreferences("nameSP",Context.MODE_PRIVATE);
           SharedPreferences.Editor editor = sp.edit();
           editor.puStirng("text",yourStirng);
           editor.apply();
       }
       public void getText(){
         return this.Text; 
       }
}

在你的片段中:

NameSP nameSp = NameSP.getInstance();
String Text = nameSP.getText();

这只是一个指南,您需要一些方法来加载和清理以及做更多的事情。只需搜索并继续...