簡體   English   中英

如何在一個片段中存儲數據以在另一個片段中獲取數據?

[英]How to store data in one fragment to get it in another fragment?

我在共享首選項類中存儲了一個字符串,並且我想在另一個片段中使用此字符串。

我認為我在Context,Application 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。

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

   }}

嘗試使用

在onCreateView()中

context = getActivity()。getApplicationContext();

在構造函數中定義您的sharedpreference:

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

並確保您使用LogedInKey鍵保存了一些內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM