简体   繁体   English

无法在片段中获取已保存的共享首选项

[英]Unable to get Saved shared preferences in the fragment

I am working on a app and while getting my shared preferences(which are saved in login activity), i am trying to get it in dashboard fragment but i am not be able to get it. 我正在开发一个应用程序,同时获取了共享的首选项(保存在登录活动中),我试图将其显示在仪表板片段中,但我无法获取它。 After this i checked whether the is saved or not so then i used 在此之后,我检查了是否已保存,然后使用了

boolean ok= editor.commit();
Toast.makeText(Login.this, "Saved: "+ok, Toast.LENGTH_LONG).show();

My toast shows message as Saved:true 我的吐司显示消息为Saved:true

After this try i am assuming that my data is saved to preferecnces but i am unable to fetch it. 尝试之后,我假设我的数据已保存到preferecnces,但是我无法获取它。 Below is my dashboard fragmenr code. 以下是我的仪表板代码。

public class dashboard extends Fragment {
private TextView comp_text,mail_text,gst_text;
private String mUsername;
private SharedPreferences mSharedPreferences;



@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    //this inflates out tab layout file.
    View x = inflater.inflate(R.layout.dashboard_frag, null);
    comp_text=(TextView)x.findViewById(R.id.company_id);
    mail_text=(TextView)x.findViewById(R.id.email_id);
    gst_text= (TextView)x.findViewById(R.id.gst_id);
    initSharedPreferences();
    Toast.makeText(getActivity(), "Logged member->  "+mUsername, Toast.LENGTH_LONG).show();
    return x;

}
private void initSharedPreferences() {
     mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    mUsername = mSharedPreferences.getString(Constants.USERNAME, "");

    }
}

Here my Toast show **logged member-> **, that means musername have nothing to print and preferences are unable get. 在这里,我的Toast显示** logged member-> **,这意味着musername没有内容可打印,并且无法获取首选项。

I'm still confused this is my point of view if you want i can show where i saved preferences. 我仍然很困惑,这是我的观点,如果您希望我可以显示保存首选项的位置。

Help will be appreciated ! 帮助将不胜感激! THANKS ! 谢谢 !

EDIT 1 ---- Here is my onResponse function where i saved preferences. 编辑1 ----这是我的onResponse函数,我在其中保存了偏好设置。

 public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
            if(response.isSuccessful()) {
                ServerResponse serverResponse = response.body();
                if(serverResponse.getMessage().equals(username)) {
                    SharedPreferences.Editor editor = mSharedPreferences.edit();
                    editor.putBoolean("LoggedIn",true);
                    editor.putString(Constants.USERNAME,serverResponse.getMessage());

                   boolean ok= editor.commit();


                    Toast.makeText(Login.this, "Saved: "+ok, Toast.LENGTH_LONG).show();
                    goToProfile();
                }
            } else {
                Gson gson = new Gson();
                ServerResponse errorResponse = null;
                try {
                    errorResponse = gson.fromJson(response.errorBody().string(), ServerResponse.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Snackbar.make(loginButton,errorResponse.getMessage(),Snackbar.LENGTH_SHORT).show();
            }
        }

Solution: 解:

Here is the simple example of storing and retrieving Shared Preferences 这是存储和检索Shared Preferences的简单示例

Setting values in Preference: 在首选项中设置值:

// MY_PREFS_NAME - a static String variable like: 
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "Elena");
 editor.putInt("idName", 12);
 editor.commit();

Retrieve data from preference: 从首选项中检索数据:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
  String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
  int idName = prefs.getInt("idName", 0); //0 is the default value.
}

more info: 更多信息:

Using Shared Preferences 使用共享首选项

Shared Preferences 共享首选项

Source: Shared Preferences Simple Example 来源: 共享首选项简单示例

In your case, you might want to replace your code as shown below: 对于您的情况,您可能需要替换代码,如下所示:

Try this 尝试这个

SharedPreferences.Editor editor = getSharedPreferences("my_prefs", MODE_PRIVATE).edit();
editor.putBoolean("LoggedIn",true);
editor.putString(Constants.USERNAME,serverResponse.getMessage());
boolean ok= editor.commit();

And then in Fragment 然后在片段

mSharedPreferences = getActivity().getSharedPreferences("prefs", MODE_PRIVATE); ;
mUsername = mSharedPreferences.getString(Constants.USERNAME, "");

If you want to logout and remove the user login, just clear the SharedPreferences : 如果要注销并删除用户登录名,只需清除SharedPreferences

SharedPreference.Editor pref = context.getSharedPreferences("prefs", MODE_PRIVATE).edit();
pref.clear();
pref.commit();

Hope this helps. 希望这可以帮助。

Try this 尝试这个

SharedPreferences.Editor editor = getSharedPreferences("my_prefs", MODE_PRIVATE).edit();;
                    editor.putBoolean("LoggedIn",true);
                    editor.putString(Constants.USERNAME,serverResponse.getMessage());

                   boolean ok= editor.commit();

And then in Fragment 然后在片段

mSharedPreferences = getActivity().getSharedPreferences("my_prefs", MODE_PRIVATE); ;
    mUsername = mSharedPreferences.getString(Constants.USERNAME, "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM