In one of my fragments, I save the clicked element:

private void saveFavorites(int position) { String name = personCategories.get(position); SharedPreferences sp = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("Favorites", name); editor.apply(); } 

After that, in another fragment I try to display the value that I saved, please tell me how you can display it, the code of the second fragment:

 public class FavoritesFragment extends BaseFragment { TextView someText; public FavoritesFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.favorites_fragment, container, false); // someText.getText(getFavorites()); } private void getFavorites() { SharedPreferences sp = getActivity().getPreferences(Context.MODE_PRIVATE); String name = sp.getString("Favorites", null); } 

    1 answer 1

    After loading the markup, you need to find the necessary view in it and assign the necessary value in the form of text to it. You tried to get the text from an uninitialized view using a nonexistent method, and even passing an argument with the value void, and even after the method was completed. Those. you in one line made 3 compilation errors, 1 logical error and one error in runtime (NPE)

    Correct the code like this:

     public class FavoritesFragment extends BaseFragment { TextView someText; public FavoritesFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.favorites_fragment, container, false); someText = v.findViewById(R.id.ТУТ_ID_ТЕКСТОВОГО_ПОЛЯ_ИЗ_РАЗМЕТКИ_ФРАГМЕНТА); someText.setText(getFavorites()); return v; } private String getFavorites() { SharedPreferences sp = getActivity().getPreferences(Context.MODE_PRIVATE); return sp.getString("Favorites", "ПУСТАЯ СТРОКА В ПРЕФАХ"); } } 
    • one
      getFavorites() , in spite of the name, returns nothing. - post_zeew
    • Replaced, with changes in `someText = (TextView) v.findViewById (R.id.textView); `but still in the line where I am trying to set the text, the text says can't resolve method setText (void); - Inkognito
    • Yes, really) I looked through the second compilation error) Corrected in the answer. - YurySPb
    • @Inkognito, your message is not informative. If you wrote with what error and on which line it fell, you could be helped. Most likely you have NPE, because There is no text field with the required ID in the layout - Juriy Spb
    • one
      @Inkognito, try asking a separate question. And so you have the usual NPE. Read here: stackoverflow.com/questions/511085/… - Yuriy SPb