Как хранить данные в одном фрагменте, чтобы получить их в другом фрагменте? - PullRequest
0 голосов
/ 26 июня 2019

Я храню строку в своем классе общих настроек и хочу использовать эту строку в другом фрагменте.

Я думаю, что я делаю что-то не так с контекстом, контекстом приложения. Я не знал о контексте вещи. Всякий раз, когда я открываю свой фрагмент профиля, приложение вылетает.

Общий класс предпочтений

public class SharedPrefs {
private static final String myPrefs = "myprefs";
private static final String LogedInKey = "Key";
private final Context context;
private final SharedPreferences sharedPreferences;
private final SharedPreferences.Editor editor;


public SharedPrefs(Context context) {
    this.context = context;
    sharedPreferences = context.getSharedPreferences(myPrefs, Context.MODE_PRIVATE);
    editor = sharedPreferences.edit();
}

public void savePref(String key) {
    editor.putString(LogedInKey, key);
    editor.commit();
}

public String getLogedInKey() {
    return sharedPreferences.getString(LogedInKey, null);
}

public void clearLogin() {
    editor.putString(LogedInKey, null);
    editor.commit();
}}

Фрагмент моего профиля:

public class ProfileFragment extends Fragment {
private Context context;
private SharedPrefs sharedPrefs=new SharedPrefs(context);

public ProfileFragment(Context context) {
    this.context = context;
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_profile, null);
    TextView userName=view.findViewById(R.id.userName);
    String a=sharedPrefs.getLogedInKey();
    userName.setText(a);

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


}}

Я просто хочу установить строку для TextView из общей ссылки.

Ответы [ 3 ]

1 голос
/ 26 июня 2019

1. На самом деле вам не нужно передавать контекст в качестве причины конструктора фрагмента, который неверен и не будет работать

    public class ProfileFragment extends Fragment {
    private SharedPrefs sharedPrefs;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
    sharedPrefs=new SharedPrefs(getActivity());
    View view = inflater.inflate(R.layout.fragment_profile, null);
    TextView userName=view.findViewById(R.id.userName);
    String a=sharedPrefs.getLogedInKey();
    userName.setText(a);

      return view;
    }
    @Override

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

   }}
0 голосов
/ 26 июня 2019

определите ваши общие предпочтения в конструкторе:

public ProfileFragment(Context context) {
this.context = context;
sharedPrefs=new SharedPrefs(context);
}

И обязательно сохраните что-нибудь с ключом LogedInKey

0 голосов
/ 26 июня 2019

Попробуйте использовать

В onCreateView ()

context = getActivity (). GetApplicationContext ();

...