开发者

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);
});


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.


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


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();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜