我在MainActivity中具有值“用户名”,请从登录会话获取。
如何将这个“用户名”用于其他活动?
我使用sharedpreference。
你能帮我吗?拜托
答案 0 :(得分:2)
尝试一下:
要写入用户名:
SharedPreferences settings = getSharedPreferences("preferences", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", username);
editor.commit();
要获取用户名:
SharedPreferences settings = getSharedPreferences("preferences", 0);
String username = settings.getString("username", ""); //sets to "" if fails
或者您可以使用捆绑包将其传递给意图:
Bundle bundle = new Bundle();
bundle.putString("username", username);
Intent intent = new Intent(this, JoinChatActivity.class);
intent.putExtras(bundle);
startActivity(this, NewActivity.class);
答案 1 :(得分:1)
尝试一下:
首先,您需要像这样在Top中初始化SharedPreferences
SharedPreferences sharedPreferences;
之后,获取值json like(username)并放置值SharedPreferences
username= obj1.getString("username");
// Using shared preference storing the data in key value pair
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", username);
editor.apply();
并在下一个活动中获取价值
SharedPreferences pref = getSharedPreferences("MyPref", 0);
String username= pref.getString("username", null);
像这样通过参数传递值
params.put("username", username);
我认为这对您有帮助
答案 2 :(得分:0)
或者您可以使用Intent传输值。例如:
这是MainActivity.class
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = new Intent (getApplicationContext(), MainActivity.class);
intent.putExtra("userName", username);
getApplicationContext().startActivities(new Intent[] {intent});
}
Other.class
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_detail);
Intent intent = this.getIntent();
String username = intent.getExtras().toString("userName");
}