Dragster
Dragster

Reputation: 13

EditText get toString

This is my code but i can't fill my string with the value put in by the user.

I've tried a lot of solutions from other sites but it won't work.

package app.android.Mel

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RedFlashlightActivity extends Activity {

private EditText text;
private TextView myRecord;
private Button myButton;

/** Called when the activity is first created. */
@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    text = (EditText) findViewById(R.id.txtName);
    myButton = (Button) this.findViewById(R.id.myButton);
    myRecord = (TextView) findViewById(R.id.myRecord);
    final String rec = text.getText().toString();

    myButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            myRecord.setText(rec);
            Toast.makeText(RedFlashlightActivity.this,rec, Toast.LENGTH_SHORT).show();
        }

    });
}
}

Upvotes: 0

Views: 4544

Answers (3)

bala singareddy
bala singareddy

Reputation: 263

Move the rec = text.getText().toString() into the OnClickListener event handler class. Then it should work. Otherwise it will take a null value, because you're using the String rec, which is constructed during the Activity creation phase.

Upvotes: 0

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43108

The point is that rec is created once at the activity creation time and doesn't change ever after( it is final ). Just replace

myRecord.setText(rec);

with

myRecord.setText(text.getText().toString());

Upvotes: 4

user479211
user479211

Reputation: 1554

    myButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        String rec = text.getText().toString();
        myRecord.setText(rec);
        Toast.makeText(RedFlashlightActivity.this,rec, Toast.LENGTH_SHORT).show();
    }
});

Upvotes: 0

Related Questions