Rob Neal
Rob Neal

Reputation: 201

Get Text not working correctly

At the moment, I'm programming the Submit button to get text from the EditText. I have implemented the necessary conditions to detect empty text. However when I run the emulator, i inserted a random string of characters and clicked Submit and I got the Toast message - please write something in the box?

Please see code and screenshot

Diary_Entry:

package com.example.ali.googleandroid;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Diary_Entry extends AppCompatActivity {

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

        EditText entryBox = (EditText) findViewById(R.id.diaryentry_box);
        Button submitEntry = (Button) findViewById(R.id.submit);

        final String writtenText = entryBox.getText().toString().trim();

        submitEntry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // check for empty text if submit button is pressed
                if ( writtenText.isEmpty() || writtenText.length() == 0 || writtenText.equals("") || writtenText == null ) {

                    Toast.makeText(getApplicationContext(), "Please write something in the box!",
                            Toast.LENGTH_LONG).show();
                } else {
                    // pass the text to display entry box and close activity
                    Intent i = new Intent(Diary_Entry.this, Entry_Dislplay.class);
                    i.putExtra("Submitted Entry", writtenText);
                    startActivity(i);
                    finish();
                }
            }
        });

    }


    public void GoBack(View v) {
        // close current activity and go back to previous activity
        onBackPressed();
        finish();
    }


}

enter image description here

Upvotes: 1

Views: 241

Answers (1)

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17142

You have to retrieve the Edittext's text when you press the button, not before that.

Move this line

final String writtenText = entryBox.getText().toString().trim();

inside the onClick callback:

public void onClick(View v) {
    String writtenText = entryBox.getText().toString().trim();
    ....
}

Upvotes: 6

Related Questions