android - 登录后如何获取 fragment 的当前用户ID

标签 android android-fragments

userLogin.class

try {
     JSONObject obj = new JSONObject(response);
     if(!obj.getBoolean("error")){
     SharedPrefManager.getInstance(getApplicationContext())
                                        .userLogin(
                                                obj.getInt("id"),
                                                obj.getString("firstname"),
                                                obj.getString("lastname"),
                                                obj.getString("s_id")
                                        );

     startActivity(new Intent(getApplicationContext(), MainActivity.class));

完成();

       }else{

       }
   } catch (JSONException e) {
           e.printStackTrace();
           Toast.makeText(getApplicationContext(),"ERROR",Toast.LENGTH_LONG).show();
     }

这是您尝试登录时的代码。 如何将当前 s_id 放入其他 Activity ,如“FragmentActivity”。 应该是这样的。登录后,它将转到 FragmentActivity,它还应该获取 s_id 的当前用户。 代码我已经放上了

Intent intentMainActivity = new Intent(LoginActivity.this, MainActivity.class);
                                intentMainActivity.putExtra("s_id", username);
                                startActivity(intentMainActivity);

但是我不知道如何进入FragmentActivity,我试过了

final String userID = getActivity().getIntent().getStringExtra("s_id");

我把下面 private void fetchNewsFeedData() { 但它仍然不起作用。 请帮我解决这个问题。 谢谢。

最佳答案

在进入 main 之前的登录 Activity 中,将用户 ID 保存到共享首选项

SharedPreferences prefs = this.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);

//set value to pref
preferences.edit().putString("s_id", username.toString()).apply();

随时随地获取数据

SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPrefs", MODE_PRIVATE);
String id = preferences.getString("s_id", "default value");

关于android - 登录后如何获取 fragment 的当前用户ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52270307/

相关文章:

java - 刷新 slider 中的 fragment

android - Eclipse 导出的 apk 崩溃

android - 新的 crashlytics (com.google.firebase.crashlytics.FirebaseCrashlytics) 不再适用于非 Google Play 设备?

android - 我应该将 onClickListener 放在自定义 ListView 的什么位置?

android - 使用相机拍照后堆内存增长更多

android - 自定义操作栏菜单项一键不响应

Android APK Intent 转到错误的链接

android - 我什么时候应该使用 fragment 中的 getActivity() 和 getContext() ?

android - SQLite 插入返回 -1 。删除包含数据库的文件夹后

android - 按下向上按钮时的自定义 Activity 转换