-3

I have an android form which consists of a login and the main file. What I want to ask is how to get the current username and display it in the main xml file.

Like for example, I logged in as "james01" and when I click the log in button, I will be redirected to the next page and in the next page there is "Welcome james01"

I kinda need your help on this.

Answers are always welcome ^^

Ms. B
  • 1,073
  • 6
  • 15
  • 26

4 Answers4

2

There will be two options

  • using Intent

  • Using preferences

using Intent

pass the parameter to the next acytivity

Intent n = new Intent(login.this, Home.class);
n.putExtra("UserName", _username);
startActivity(n);

In your Home page:

Bundle extras = getIntent().getExtras();
if(extras!=null)
{
    userName.setText("Welcome to "+extras.getString("UserName"));
}

Using Preferences

In Your login Page

preferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = preferences.edit();
edit.putString("pref_userName", userName);
edit.commit();

In your Home page

pref_userName = preferences.getString("pref_userName", "n/a");
userName.setText("Welcome to "+pref_userName);

If you have more activities and want to show username in all activities then I suggest to use Preferences. So this will be simple and one more thing is

If you are using preferences then don't forget to putstring null when you are logout from the app

Ram kiran Pachigolla
  • 20,897
  • 15
  • 57
  • 78
  • in the intent section, particularly in n.putExtra("UserName", _username); is the term UserName declared or its just like a tag? and _username is my column name right? and is it ok not to put textviews anymore? simply display it? – Ms. B Jan 18 '13 at 07:19
1

The easiest way to do this is to pass the username to the 2nd activity in the intent you're using to start the activity:

Intent intent = new Intent(getBaseContext(), SecondActivity.class);
intent.putExtra("USERNAME", username);
startActivity(intent);

Then in the second activity:

String username = getIntent().getStringExtra("USERNAME");

check How do I pass data between Activities in Android application?

Community
  • 1
  • 1
Nermeen
  • 15,883
  • 5
  • 59
  • 72
0
Intent i = new Intent(currentActivity.this,NextActivity.class);
i.putExtra("name",name.getText.toString());
StartActivity(i);

Get name NextActivity.class

Intent i = getIntent();
String name = i.getStringExtra("name");

and set this name to textview or toast.

MuraliGanesan
  • 3,233
  • 2
  • 16
  • 22
0

LoginAcvtivity.java

intent.putExtra("USERNAME",_userText.getText().toString());

Destinantion class.java

String username = getIntent().getStringExtra("USERNAME");

final TextView textViewToChange = (TextView) findViewById(R.id.username);
textViewToChange.setText(username);

In your xml create a < texview

android:id="@+id/username"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textStyle="normal|bold|italic" />

This is an example from an app I am working on.