I send a request from imei to the server and get a token. But when you exit the application and start it again, a new token is issued, I need only 1. And so that I always work with only one, how to solve this problem?

if(sPref==null) { Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://tkachenkodevelop.ru/autoexpert/") .addConverterFactory(GsonConverterFactory.create()) .build(); mServerApi = retrofit.create(API.IServerApi.class); //mServerApi = API.getRetrofit(getString(R.string.api_url), this).create(API.IServerApi.class); Call<Token> call = (Call<Token>) mServerApi.getToken(imei); call.enqueue(new Callback<Token>() { @Override public void onResponse(Call<Token> call, Response<Token> response) { // response.body().getAccessToken(); Log.d("qwe", response.body().getAccessToken()); //mPhoneEdit.setText(response.body().getAccessToken()); mToken = response.body().getAccessToken(); saveText(mToken); } @Override public void onFailure(Call<Token> call, Throwable t) { //Log.d("error",t.toString()); } }); }else { sharedPreferences = getSharedPreferences("SavedIdToken", MODE_PRIVATE); mToken = sharedPreferences.getString("Token", ""); } 

where

 void saveText(String token) { sPref = this.getSharedPreferences("SavedToken", Context.MODE_PRIVATE); SharedPreferences.Editor ed = sPref.edit(); ed.putString("Token", token); ed.apply(); } 
  • See the last option in the answer in the question-duplicate - YuriySPb
  • @YuriSPb, the question is a duplicate of exactly what you noted. - Vladyslav Matviienko
  • Save it somewhere. To file, to database, to SharedPreferences. - Vladyslav Matviienko
  • @YuriySPb, if one of the answers also contains an answer to this question, this does not mean that the question is a duplicate. - Vladyslav Matviienko
  • @metalurgus, OK, took a double) - Yuriy SPb

1 answer 1

Try to save in SharedPreferences:

 //так записываешь SharedPreferences userDetails = this.getSharedPreferences("userdetails", MODE_PRIVATE); SharedPreferences.Editor edit = userDetails.edit(); edit.putString("token", token).commit(); 

Next, when you start the application, you check:

 token = userDetails.getString("token", "null"); if (!token.equals("null")) { //если токен уже есть, то выполняешь действия без авторизации } else { //если токена нет, то авторизация } 

When logging out, you delete / write "null" instead of token:

 SharedPreferences.Editor edit = userDetails.edit(); //очищаешь edit.clear(); //записываешь null edit.putString("token", "null"); 
  • Record at Destroy? - Martinez Toni
  • @MartinezToni, when getting a token. - Nikotin N
  • gives the error: 'java.lang.String android.content.SharedPreferences.getString (java.lang.String, java.lang.String)' on a null object reference - Martinez Toni
  • at logout? Where is it? - Martinez Toni
  • @MartinezToni in which line gives an error? Well, I understand the logout is not needed, so just write down the token. - Nikotin N