user9251161
user9251161

Reputation:

SharedPreferences not saves

Ok, i have an authorization app, where i need to save the clientID, clientSecret, accessToken and refreshToken. I tried to save, but i done something wrong, he saves only 1 value for all fields. Check the code please. That's a little long code, the sharedPreference part is in the end.

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. What's wrong in code?

Upvotes: 4

Views: 138

Answers (7)

Uthaya
Uthaya

Reputation: 373

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

Upvotes: 1

Ratilal Chopda
Ratilal Chopda

Reputation: 4220

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

Upvotes: 1

Rajan Kali
Rajan Kali

Reputation: 12953

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

Upvotes: 1

Raul
Raul

Reputation: 104

use .commit()

It returns true if the save works, false otherwise.

Upvotes: 1

Hardik Lakhani
Hardik Lakhani

Reputation: 1564

Look like your value is replaced just because you are using the same 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");

Upvotes: 1

3iL
3iL

Reputation: 2176

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.

Upvotes: 1

AskNilesh
AskNilesh

Reputation: 69744

If you need to save different data in SharedPreferences you need to use different key

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

Upvotes: 4

Related Questions