【问题标题】:Shared Preference value to API Get methodAPI Get 方法的共享首选项值
【发布时间】:2020-09-12 07:19:26
【问题描述】:

我是 android 和改造的新手。我希望将存储在共享首选项中的用户 ID 放入 api 调用中。 我已经开发了 this.how 用共享偏好值替换 {uid}

API接口

        @GET("/Account/{uid}/friends")
        Call<List<TblFriends>> getfriends(@Path("uid") String uid);

活动

 public void getFriends()
   {
    Api api = RetrofitClient.getInstance().create(Api.class);

    Call<List<TblFriends>> call = api.getfriends();
    call.enqueue(new Callback<List<TblFriends>>() {
        @Override
        public void onResponse(Call<List<TblFriends>> call, Response<List<TblFriends>> response)

        {

            if (response.isSuccessful())
            {
                List<TblFriends> tblFriends = response.body();
                friendsAdapter.setData(tblFriends);
                recyclerView.setAdapter(friendsAdapter);

                //    Log.e("success",response.body().toString());
            }

        }
        @Override
        public void onFailure(Call<List<TblFriends>> call, Throwable t) {

            Log.e("failure",t.getLocalizedMessage());
        }
    });
}

共享偏好代码用于登录活动以获取用户 ID,这是登录中的完整代码

public static String globalPreferenceName = "proofile";


        SharedPreferences.Editor editor = 
        getSharedPreferences(globalPreferenceName,MODE_PRIVATE).edit();
       //UserID
        editor.putString("token",s);  
       editor.putString("token2",JWTUtils.getJSon(token));
        editor.commit();

                

【问题讨论】:

  • 发布您的共享偏好代码。
  • 你知道如何从 SharedPreference 中获取价值吗?

标签: java android networking retrofit retrofit2


【解决方案1】:
Get your globalPreferenceName shared preference as below.
SharedPreferences sharedPref = context.getSharedPreferences(globalPreferenceName,Context.MODE_PRIVATE);

By using sharedPref get your token2 as below.
String uid = sharedPref.getString("token2"), defaultValue);

Then use uid as below,
 Call<List<TblFriends>> call = api.getfriends(uid);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 2019-04-28
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多