Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save access_token via shared preferences android

My app gets some responce from server, and in that responce I also receive access token, which I have to use in my further operations, in general I managed to fetch this token from my responce and now I can see it in textView. But anyway I have to create smth like refreshing the following token, because I think that my users won't too happy to log in my app a lot of times, after current token will expire. So right now I have very serious question, like how to insert the following token, which I can get from my responce into my request:

@Headers({"Content-type: application/json",
        "Authorization: Bearer my token"})
@GET("/v1/message/list")
Call<ListOfMess> getInMess(@Query("type") int type, @Query("offset") int offset);

right now I have to insert the last token every half an hour, because I won't be able to get any data. I tried to insert the following token into my retrofit initialization:

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://server/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

But it didn't work properly. So after some period of time I got know that I can store the following token by sharedpreferences and than insert it everywhere, but I don't know how I can create it. I hope that you will help mw with the following problem. And also if you know the way of refreshing my token after some period of time by some request, I will be happy to see your answer)) Sorry for my bad language skills.

like image 603
Andrew Avatar asked Mar 06 '23 17:03

Andrew


1 Answers

    //Save token here
    String token = "Some token From Server";
    SharedPreferences preferences = getActivity().getSharedPreferences("MY_APP",Context.MODE_PRIVATE);
    preferences.edit().putString("TOKEN",token).apply();


    //Retrieve token wherever necessary
    SharedPreferences preferences = getActivity().getSharedPreferences("MY_APP",Context.MODE_PRIVATE);
    String retrivedToken  = preferences.getString("TOKEN",null);//second parameter default value.
like image 167
Gnanendra Kumar Avatar answered Mar 08 '23 23:03

Gnanendra Kumar