Question

I am not able to get the text from EditText and convert it to string and then display the entered text in the toast. Toast only shows a small blank bar with no text in it. here is my code.

package com.asssra.textinput;

import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.widget.*;

public class MainActivity extends Activity {

    EditText t;
    Button b;
    String s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        t = (EditText) findViewById(R.id.box);

        b = (Button) findViewById(R.id.button);

        s = t.getText().toString();

        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}
Was it helpful?

Solution

Move this

 s = t.getText().toString();

You are getting text from edittext just after initialization. Just move it onClick

inside of ClickListener of the button

 b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        s = t.getText().toString();
        Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
        }
    });

OTHER TIPS

Why didn't we accomplished this using casting?

EditText getNameField = (EditText) findViewById(R.id.your_edit_text);
String castToString = (String) getNameField.getText();
return castToString;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top