litterbugkid
litterbugkid

Reputation: 3666

Get value held by Android EditText field using the identifier

I got the id dynamically as an integer using getIdentifier(). I want to be able to get the value held by the EditText field using the integer id.

I should add this method i'm writing is not within an Activity, it's in a seperate non-Activity class.

Upvotes: 0

Views: 1112

Answers (4)

skynet
skynet

Reputation: 9908

You can use

String value = ((EditText) findViewById(R.id.edittext)).getText();

If you are using a separate class, you should pass a reference to the EditText into that class. First get the reference

setContentView(R.layout.yourlayout);
EditText editText = (EditText) findViewById(getResources()
        .getIdentifier("edittext", "id", "com.yourpackage"));

then pass it to your other class, and use getText on it there. Make sure you only try to access the EditText while the Activity is active.

There is a warning for the getIdentifier method, so you should only be using it if you have no other choice:

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

Upvotes: 1

jazz
jazz

Reputation: 1216

String value = ((EditText) findViewById(R.id.edittext)).getText().toString;

toString() is required, as getText() returns editable

Upvotes: 0

GalDude33
GalDude33

Reputation: 7130

Use this code:

EditText et=(EditText) findViewById(your_editText_id);
CharSequence text = et.getText();
String textS=text.toString();

Upvotes: 0

freshDroid
freshDroid

Reputation: 509

Is this what you are asking for?

String ed1 = ((EditText) findViewById(R.id.value)).getText().toString();

Upvotes: 0

Related Questions