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

时间:2018-10-22 06:42:29

标签: java android fragment sharedpreferences

我正在开发一个应用程序,同时获取了共享的首选项(保存在登录活动中),我试图在仪表板片段中获取它,但我却无法获取它。在此之后,我检查了是否已保存,然后使用了

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

我的吐司显示的消息为 Saved:true

在尝试之后,我假设我的数据已保存到preferecnces,但是我无法获取它。下面是我的仪表板代码。

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

    }
}

这是我的Toast节目**登录的会员-> **,这意味着musername无需打印,首选项无法获取。

我仍然很困惑,这是我的观点,如果您希望我可以显示保存首选项的位置。

我们将不胜感激! 谢谢!

编辑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();
            }
        }

2 个答案:

答案 0 :(得分:2)

解决方案:

这是存储和检索C

的简单示例

设置“首选项”中的值:

fun main(args: Array<String>) {
val user = User()
user.id = 10
user.name = "test"
var userNew = user.toUserNew()
println(userNew.id) // output is 10
println(userNew.name)// output is test
 }


class User() 
{
var id: Int? = null
var name: String? = null

fun toUserNew(): UserNew {
    val userNew = UserNew()
    userNew.id = id
    userNew.name = name
    return userNew
  }
}

  class UserNew() {
  var id: Int? = null
  var name: String? = null
  }

从偏好设置中检索数据:

Shared Preferences

更多信息:

Using Shared Preferences

Shared Preferences

来源:Shared Preferences Simple Example

您可能需要替换如下所示的代码:

尝试一下

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

然后在片段

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.
}

如果要注销并删除用户登录,只需清除SharedPreferences.Editor editor = getSharedPreferences("my_prefs", MODE_PRIVATE).edit(); editor.putBoolean("LoggedIn",true); editor.putString(Constants.USERNAME,serverResponse.getMessage()); boolean ok= editor.commit();

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

希望这会有所帮助。

答案 1 :(得分:1)

尝试一下

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

                   boolean ok= editor.commit();

然后在片段

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