-6

I have value 'username' in MainActivity, get from login session.

How i can put this 'username' to other activity?

I use sharedpreference.

Can you help me? Pleasee

3 Answers3

2

Try this:

To write the username:

SharedPreferences settings = getSharedPreferences("preferences", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", username);
editor.commit();

To get the username:

SharedPreferences settings = getSharedPreferences("preferences", 0);
String username = settings.getString("username", ""); //sets to "" if fails

Or you can pass it through the intent using a bundle:

Bundle bundle = new Bundle();
bundle.putString("username", username);
Intent intent = new Intent(this, JoinChatActivity.class);
intent.putExtras(bundle);
startActivity(this, NewActivity.class);
ThatCampbellKid
  • 561
  • 1
  • 5
  • 19
1

Try this:

First you initialize the SharedPreferences in Top like this

  SharedPreferences sharedPreferences;

after that get the value json like(username) and put the value 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();

And get the value in next activity like this

 SharedPreferences pref = getSharedPreferences("MyPref", 0);
 String username= pref.getString("username", null);

Pass the value in parameter like this

  params.put("username", username);

i think it helps you

Android Geek
  • 8,956
  • 2
  • 21
  • 35
0

Or you can transfer the value using Intent. for example:

This is 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");
}
Ticherhaz FreePalestine
  • 2,738
  • 4
  • 20
  • 46