简体   繁体   English

SharedPreferences不保存

[英]SharedPreferences not saves

Ok, i have an authorization app, where i need to save the clientID, clientSecret, accessToken and refreshToken. 好的,我有一个授权应用程序,我需要保存clientID,clientSecret,accessToken和refreshToken。 I tried to save, but i done something wrong, he saves only 1 value for all fields. 我试图保存,但我做错了,他只为所有字段保存了1个值。 Check the code please. 请检查代码。 That's a little long code, the sharedPreference part is in the end. 这是一个很长的代码,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();
}}

In last method when i try to get the data the client id gets 168e3903996c90818ecabaf1c60ff4108a2f6d438e8bcb788a7fe5ef5224d1 the clientSecret, AccessToken and refreshToken too. 在最后的方法,当我试图让客户端ID获取的数据168e3903996c90818ecabaf1c60ff4108a2f6d438e8bcb788a7fe5ef5224d1的clientSecret,和的accessToken太refreshToken。 What's wrong in code? 代码有什么问题?

If you need to save different data in SharedPreferences you need to use different key 如果需要在SharedPreferences保存不同的数据,则需要使用不同的密钥

Like this 像这样

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

than call like this 比这样打电话

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

than get all data like this 比得到这样的所有数据

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

What you're trying is this: 你正在尝试的是这个:

saveData(access_token);
saveData(refresh_token);

What you can do: 你可以做什么:

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

It only saves one value, as you said, because you're re-writing your shared pref. 正如你所说,它只保存了一个值,因为你正在重写你的共享首选项。

Look like your value is replaced just because you are using the same id. 看起来你的值被替换只是因为你使用相同的id。

Below code may work for you. 下面的代码可能适合您。

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

and call this method like below. 并调用此方法,如下所示。

saveData("client_id","abcded");

use .commit() 使用.commit()

It returns true if the save works, false otherwise. 如果保存有效,则返回true,否则返回false。

It's because you are trying to save all values in same key, try different keys for each value as in 这是因为您尝试将所有值保存在同一个键中,请为每个值尝试不同的键

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

And while saving data 同时保存数据

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

Try this 尝试这个

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

GET DATA 获取数据

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

Your saving data is perfect only the problem is way of accessing and also small change in when you saving the data 您的保存数据是完美的,只有问题是访问方式,以及保存数据时的小变化

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

Here is which key you pass same key to retrieving the data every time pass different keys below details. 以下是每次通过不同密钥详细信息时传递相同密钥以检索数据的密钥。

Before saving token do like this: 保存令牌前请执行以下操作:

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

Then retrieving the data like this : 然后检索这样的数据:

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

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

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