SharedPreferences不会保存

时间:2018-02-01 07:19:36

标签: java android sharedpreferences

好的,我有一个授权应用程序,我需要保存clientID,clientSecret,accessToken和refreshToken。 我试图保存,但我做错了,他只为所有字段保存了1个值。请检查代码。 这是一个很长的代码,sharedPreference部分最终。

public class FragmentRegistration extends Fragment {
View mainView;

EditText name, username, email, password;
Button button;

ApiClient apiClient = ApiClient.getInstance();

SupportopObj supportopObj = new SupportopObj();
SupportopObjActivate supportopActivate = new SupportopObjActivate();
SupportObjToken supportopToken = new SupportObjToken();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mainView = inflater.inflate
            (R.layout.registration, container, false);

    username = mainView.findViewById(R.id.username);
    email = mainView.findViewById(R.id.email);
    password = mainView.findViewById(R.id.password);
    name = mainView.findViewById(R.id.name);
    button = mainView.findViewById(R.id.register);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String s = name.getText().toString();
            String split[] = s.split(" ");

            supportopObj.setFirstName(split[0]);
            supportopObj.setLastName(split[1]);
            supportopObj.setUsername(username.getText().toString());
            supportopObj.setEmail(email.getText().toString());
            supportopObj.setPassword(password.getText().toString());

            supportopActivate.setUsername(supportopObj.getUsername());
            supportopActivate.setEmail(supportopObj.getEmail());
            supportopActivate.setPassword(supportopObj.getPassword());
            supportopActivate.setType("generic");

            registerCall();


            getSaveData();
        }
    });

    return mainView;
}


public void registerCall() {

    Call<ResponseBody> call = apiClient.registration(supportopObj);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                //VersionDataInfo versionDataInfo = response.body();
                clientCall();

            } else {
                Toast.makeText(getActivity(), "Something went wrong", Toast.LENGTH_SHORT).show();
                clientCall();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(getActivity(), "Error...", Toast.LENGTH_SHORT).show();
        }
    });
}

public void clientCall() {
    Call<ResponseBody> callActive = apiClient.activation(supportopActivate);
    callActive.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            if (response.isSuccessful()) {

                try {
                    String data = response.body().string();
                    JSONObject obj = new JSONObject(data);
                    String client_id = obj.getString("client_id");
                    String client_secret = obj.getString("client_secret");

                    saveData(client_id);
                    saveData(client_secret);

                    tokenCall(client_id, client_secret);

                } catch (JSONException | IOException e) {
                    e.printStackTrace();
                }

            } else {
                Toast.makeText(getActivity(), "error", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(getActivity(), "Error in activation", Toast.LENGTH_SHORT).show();
        }
    });
}

public void tokenCall(String client_id, final String client_secret) {
    Call<ResponseBody> token = apiClient.getToken("password", client_id, client_secret,
            supportopActivate.getEmail(), supportopActivate.getPassword());

    token.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                try {
                    String dataAccess = response.body().string();
                    JSONObject obj = new JSONObject(dataAccess);

                    String access_token = obj.getString("access_token");
                    String refresh_token = obj.getString("refresh_token");
                    String client_id = obj.getString("client_id");

                    supportopToken.setGrantType("refresh_token");
                    supportopToken.setClientId(client_id);
                    supportopToken.setClientSecret(client_secret);
                    supportopToken.setRefreshToken(refresh_token);

                    saveData(access_token);
                    saveData(refresh_token);

                    newTokenCall();

                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getActivity(), "Something wrong.....", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(getActivity(), "You're on failure", Toast.LENGTH_SHORT).show();
        }
    });
}

public void newTokenCall() {
    Call<ResponseBody> newToken = apiClient.newToken(supportopToken);
    newToken.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                Toast.makeText(getActivity(), String.valueOf(response.body()), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(getActivity(), "You're on failure getting new Token", Toast.LENGTH_SHORT).show();
        }
    });
}

public void saveData(String data) {
    SharedPreferences preferences = this.getActivity().getSharedPreferences("Saved_data", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("Data", data).apply();
}

public void getSaveData() {
    SharedPreferences preferences = this.getActivity().getSharedPreferences("Saved_data", Context.MODE_PRIVATE);
    String client_id = preferences.getString("Data", "client_id");
    String client_secret = preferences.getString("Data", "client_secret");
    String access_token = preferences.getString("Data", "access_token");
    String refresh_token = preferences.getString("Data", "refresh_token");
    Toast.makeText(getActivity(), client_id + " " + client_secret
            + " " + access_token + " " + refresh_token,Toast.LENGTH_SHORT).show();
}}

在最后一种方法中,当我尝试获取数据时,客户端ID也获得168e3903996c90818ecabaf1c60ff4108a2f6d438e8bcb788a7fe5ef5224d1 clientSecret,AccessToken和refreshToken。代码中有什么问题?

7 个答案:

答案 0 :(得分:3)

如果您需要在SharedPreferences中保存不同的数据,则需要使用不同的密钥

喜欢这个

public void saveData(String key,String data) {
    SharedPreferences preferences = this.getActivity().getSharedPreferences("Saved_data", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(key, data).apply();
}

比这样打电话

saveData("client_id",client_id);
saveData("client_secret",client_secret);
saveData("access_token",access_token);      
saveData("refresh_token",refresh_token);

获取所有这样的数据

public void getSaveData() {
    SharedPreferences preferences = this.getActivity().getSharedPreferences("Saved_data", Context.MODE_PRIVATE);
    String client_id = preferences.getString("client_id", "client_id");
    String client_secret = preferences.getString("client_secret", "client_secret");
    String access_token = preferences.getString("access_token", "access_token");
    String refresh_token = preferences.getString("refresh_token", "refresh_token");
    Toast.makeText(getActivity(), client_id + " " + client_secret
            + " " + access_token + " " + refresh_token,Toast.LENGTH_SHORT).show();
}}

答案 1 :(得分:1)

你正在尝试的是:

saveData(access_token);
saveData(refresh_token);

你能做什么:

saveData(access_token, refresh_token);

public void saveData(String token1, String token2) {
    SharedPreferences preferences = this.getActivity().getSharedPreferences("Saved_data", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("Data1", token1).apply();
    editor.putString("Data2", token2).apply();
}

正如您所说,它只保存了一个值,因为您正在重写您的共享首页。

答案 2 :(得分:1)

看起来你的值被替换只是因为你使用相同的id。

以下代码可能适合您。

public void saveData(String key_name,String data) {
    SharedPreferences preferences = this.getActivity().getSharedPreferences("Saved_data", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(key_name, data).apply();
}

并调用此方法,如下所示。

saveData("client_id","abcded");

答案 3 :(得分:1)

使用.commit()

如果保存有效,则返回true,否则返回false。

答案 4 :(得分:1)

这是因为您尝试将所有值保存在同一个键中,请为每个值尝试不同的键,如

public static final String KEY_ACCESS_TOKEN = "accessToken";
public static final String KEY_REFRESH_TOKEN = "refreshToken";
public static final String KEY_CLIENT_ID = "clientId";
public static final String KEY_CLIENT_SECRET = "clientSecret";

public void saveData(String key,String data) {
    SharedPreferences preferences = this.getActivity().getSharedPreferences("Saved_data", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(key, data).apply();
}

public void getSaveData() {
    SharedPreferences preferences = this.getActivity().getSharedPreferences("Saved_data", Context.MODE_PRIVATE);
    String client_id = preferences.getString(KEY_CLIENT_ID , "client_id");
    String client_secret = preferences.getString(KEY_CLIENT_SECRET , "client_secret");
    String access_token = preferences.getString(KEY_ACCESS_TOKEN , "access_token");
    String refresh_token = preferences.getString(KEY_REFRESH_TOKEN , "refresh_token");
    Toast.makeText(getActivity(), client_id + " " + client_secret
            + " " + access_token + " " + refresh_token,Toast.LENGTH_SHORT).show();
}}

保存数据时

saveData(KEY_ACCESS_TOKEN ,access_token);
saveData(KEY_REFRESH_TOKEN ,refresh_token);
saveData(KEY_CLIENT_ID ,client_id);
saveData(KEY_CLIENT_SECRET ,client_secret);

答案 5 :(得分:1)

试试这个

保存数据

public void saveData(String data) {
    SharedPreferences preferences = this.getActivity().getSharedPreferences("Saved_data", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("client_id",client_id).apply();
    editor.putString("client_secret",client_secret).apply();
    editor.putString("access_token",access_token).apply();
    editor.putString("refresh_token",refresh_token).apply();
}

获取数据

    public void getSaveData() {
    SharedPreferences preferences = this.getActivity().getSharedPreferences("Saved_data", Context.MODE_PRIVATE);
    String client_id = preferences.getString("client_id", "client_id");
    String client_secret = preferences.getString("client_secret", "client_secret");
    String access_token = preferences.getString("access_token", "access_token");
    String refresh_token = preferences.getString("refresh_token", "refresh_token");
    Toast.makeText(getActivity(), client_id + " " + client_secret
            + " " + access_token + " " + refresh_token,Toast.LENGTH_SHORT).show();
}

答案 6 :(得分:1)

您的保存数据非常完美,只有问题是访问方式,以及保存数据时的小变化

editor.putString("Data", data).apply(); 

以下是在每次通过细节下面的不同键时,通过相同键检索数据的键。

在保存令牌之前,请执行以下操作:

public void saveData(String data) {
SharedPreferences preferences = 
this.getActivity().getSharedPreferences("Saved_data", 
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("client_id", data).apply();
}

然后检索这样的数据:

public void getSaveData() {
SharedPreferences preferences = 
this.getActivity().getSharedPreferences("Saved_data", 
 Context.MODE_PRIVATE);
String client_id = preferences.getString("client_id", null);   
Toast.makeText(getActivity(), client_id  ,Toast.LENGTH_SHORT).show();
}