andyguy
andyguy

Reputation: 23

Best way to pass variable value from one class to another android

I am very new in android, i am learning.

I have created a simple login system, where it will communicate with php. Its working fine,

Right now there is 3 activity,

1st - login 2nd - menu 3rd - view

in login, they have to specify their username, i wish to get the username in view (3rd) How can i get it? I tried google and read, none of them working for me :(

i am using

    final Button btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
EditText name = (EditText)findViewById(R.id.name);
});

Upvotes: 1

Views: 7077

Answers (3)

Spoike
Spoike

Reputation: 121772

You can get text from an EditText widget using getText() followed by toString(). So your code should be:

final Button btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
    EditText nameWidget = (EditText) findViewById(R.id.name);
    String username = nameWidget.getText().toString();
});

Upvotes: 0

Jim Blackler
Jim Blackler

Reputation: 23169

What you're looking for are intent 'extras'. These are extra pieces of information carried from Activity to Activity on the Intent.

There's an example in the source for my application Google Moderator for Android.

Creating an Intent that carries some extra information (here, 'series ID'):

  Intent intent = new Intent(activity, TopicActivity.class);
  intent.putExtra("seriesId", seriesId);
  //...
  activity.startActivity(intent);

http://www.google.com/codesearch/p?hl=en#RbTgvHmKhC4/trunk/src/com/google/android/apps/moderator/TopicListEntry.java&l=49

On another Activity, retrieving the value from the same intent (now the launching intent)'s extras:

   int seriesId = getIntent().getIntExtra("seriesId", -1);

http://www.google.com/codesearch/p?hl=en#RbTgvHmKhC4/trunk/src/com/google/android/apps/moderator/TopicActivity.java&l=183

In this example, -1 is the value that will be returned if there is no "seriesId" carried with the extra.

Upvotes: 2

Haphazard
Haphazard

Reputation: 10948

You can set the user name to a public, static value so it can be reached from any class within your application.

Or you can pass it around your Activities using the Intent method putExtra(..) http://developer.android.com/reference/android/content/Intent.html

Upvotes: 0

Related Questions