SharedPreferences无法保存

4

好的,我有一个授权应用程序,需要保存客户端ID、客户端密钥、访问令牌和刷新令牌。我尝试保存,但做错了些什么,他只保存所有字段的一个值。请检查代码。

这是一段有点长的代码,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,客户端密钥、访问令牌和刷新令牌也会发生这种情况。代码有什么问题?

1
尝试发布相关代码,这样易于理解并获得有意义的回复! - 3iL
因为您将所有值都放在一个名为“Data”的键中,所以请使用不同的键分配不同的值。请遵循Nilesh Rathod提供的答案。 - Nirmal Prajapat
7个回答

4
如果您需要在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();
}}

@HaykMkrtchyan 很高兴能帮助你。 - AskNilesh
我投了票。他说我必须等待9分钟才能投票你的答案。 - user9251161
请给我的问题投票。我需要稍微提高一下声望。 - user9251161

1

What you're trying is this:

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

正如你所说,它只保存一个值,因为你正在重写共享首选项。


请给我的问题投票。我需要更高的声誉。 - user9251161

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

请给我的问题投票。我需要稍微提高一下声望。 - user9251161

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

请给我的问题投票。我需要稍微提高一下声望。 - user9251161

1
尝试这个:

保存数据

Save Data

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

请给我的问题投票。我需要一个稍微高一点的声誉。 - user9251161
@HaykMkrtchyan 是的,当然可以。 - Ratilal Chopda
1
非常感谢。 - user9251161

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

请投票支持我的问题。我需要提高一点声望。 - user9251161

1

使用.commit()

如果保存成功则返回true,否则返回false。


.commit()和.apply()有微小的区别。.commit()返回一个布尔值,表示操作是否成功,而.apply()则不返回任何值。 - Android Dev
请给我的问题投票。我需要稍微提高一下声望。 - user9251161

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接