在 Android 上访问当前用户 ID

Access the current user id on Android

我有一个问题,那就是...我有一个用户登录的 LoginActivity 和一个 DashboardActivity,如果用户成功登录,他将被重定向到仪表板。

当我登录时,我得到的 json 对象如下:

{
  "id": 9,
  "email": "mario@gmail.com",
  "password": "123456"
}

最后。我的问题是,有没有办法在 DashboardActivity 中访问用户 ID?

我使用的堆栈如下: Android Studio、Retrofit、GSON 和 Node.js。

祝你有愉快的一天!

有以下几种方式,您可以通过这些方式访问仪表板中的用户标识activity。

  • 使用捆绑: 在启动仪表板之前 activity 您可以设置如下所示的意图值:

    Intent i = new Intent(LoginActivity.this, DashboardActivity.class);
    String id= valueofId;// 在这里设置id的值。 i.putExtra("STRING_I_NEED", id);

并且您可以检索此值,如下所示: 字符串 userId;

Bundle extras = getIntent().getExtras();
if(extras != null) {
    userId = extras.getString("STRING_I_NEED");
}
  • 使用共享首选项: 您可以在 loginActivity 中保存数据并在 Dashboard 中检索activity

如何保存数据:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score_key), newHighScore);
editor.commit();

如何获取数据:

Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
        getString(R.string.preference_file_key), Context.MODE_PRIVATE);

就是这样。 编码愉快! 谢谢!