如何在一个片段中存储数据以在另一个片段中获取数据?

时间:2019-06-26 00:19:23

标签: java android android-fragments sharedpreferences

我在共享首选项类中存储了一个字符串,我想在另一个片段中使用此字符串。

我认为我在Context(应用程序上下文)中做错了。 我不知道有关上下文的事情。 每当我打开“个人资料片段”时,应用就会崩溃。

共享首选项类别

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 个答案:

答案 0 :(得分:1)

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

   }}

答案 1 :(得分:0)

尝试使用

在onCreateView()

context = getActivity()。getApplicationContext();

答案 2 :(得分:0)

在构造函数中定义您的sharedpreference:

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

并确保您使用键LogedInKey保存了一些东西