Hot questions for Using Android EditText in gettext

Question:

For example in the code below a and b and c are equal.

EditText editText;
editText = (EditText) findViewById(R.id.edttxt);

editText.setText("1234");

int a, b, c;
a = editText.length();
b = editText.getText().length();
c = editText.getText().toString().length();

What is difference between length() and getText().length() and getText().toString().length()?


Answer:

.length() and getText().length() are identical in their current implementation.

.getText().toString().length() will convert the CharSequence into a plain String, then compute its length. I would expect that to return the same value as the other two in many cases. However, if the CharSequence is something like a SpannedString, I cannot rule out the possibility that there is some type of formatting span (e.g., ImageSpan) that affects length calculations.

Question:

I just want the editText.getText().toString() to get the normal String inserted to the EditText but instead I'm getting it all uppercase no matter what.

Relevant XML:

    <LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/first_name_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/first_name_text"
        android:textSize="20sp"
        />

    <EditText
        android:id="@+id/first_name_edit_text_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/first_name_hint_text"
        />

    </LinearLayout>

Relevant Java:

sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferencesEditor = sharedpreferences.edit();

    signUpButton.setOnClickListener(new View.OnClickListener()
    {   
        @Override
        public void onClick(View v) 
        {
            final String firstName = sharedpreferences.getString(FIRST_NAME_KEY, "");
            sharedPreferencesEditor.putString(FIRST_NAME_KEY, firstNameEditText.getText().toString());
            sharedPreferencesEditor.apply();

            signUpButton.setText(firstName);
        }
    });

The firstName which is a final String variable is always uppercase. Now whys that? and how do i solve it?


Answer:

Is this at all related to your problem? Why is my Button text forced to ALL CAPS on Lollipop?

I would try adding android:textAllCaps="false" to the button.

Question:

So this is another problem that has been brought up a million times, but I'm still doing something wrong. Using EditText.getText() is returning an empty string.

I'm doing this in a small custom dialog I've made. I'm building it with the AlertDialog Builder, which might be causing the issue? I really don't know at this point.

Some things I've tried/notes on what I know about the issue:

  • I'm checking for text in the OK button's click listener, so I'm not trying to get a value before there would be one, which was a common error I saw.

  • I have ID's set for the EditText objects in my XML and the debugger seems to show that I'm referencing them properly.

  • I've tried defining the EditText objects outside of the onCreateDialog method and that didn't change things (though I am curious which is better practice).

  • Using EditText.setText() before getText() will allow it to return the argument used in setText(), but it doesn't seem to be fetching a value input by the user.

Here is my custom Dialog Fragment:

public class GPSLocationDialogFragment extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        LayoutInflater inflater = getActivity().getLayoutInflater();
        final View view = inflater.inflate(R.layout.gps_dialog, null);

        final EditText latitudeText = (EditText) view.findViewById(R.id.latitude);
        final EditText longitudeText = (EditText) view.findViewById(R.id.longitude);

        // Define the dialog
        builder.setView(inflater.inflate(R.layout.gps_dialog, null))
                .setMessage("Manually input a GPS address")

                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        Log.d("myTag", "Text: " + latitudeText.getText()); // This prints ""

                        // These throw errors since they're trying to parse "" as a double
                        double latitude = Double.parseDouble(latitudeText.getText().toString());
                        double longitude = Double.parseDouble(longitudeText.getText().toString());
                    }
                })

                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        dialog.cancel();
                    }
                });

        // Create the AlertDialog object and return it
        return builder.create();
    }
}

Here is how I'm calling the Dialog from my Activity:

GPSLocationDialogFragment gpsDialog = new GPSLocationDialogFragment();

gpsDialog.show(getFragmentManager(), "GPSDialog");

And here is my layout .xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/longitude"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:hint="@string/longitude"
        android:inputType="numberSigned|numberDecimal" />
    <EditText
        android:id="@+id/latitude"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:hint="@string/latitude"
        android:inputType="numberSigned|numberDecimal" />
</LinearLayout>

If more context is necessary I can share it, I tried to simplify to just the relevant code.


Answer:

Try changing this:

builder.setView(inflater.inflate(R.layout.gps_dialog, null))

to this:

builder.setView(view)

What's happening is that you inflate gps_dialog xml and turn its layout hierarchy into a View. Then you find the EditText's and a assign a reference to them.

However, by calling setView(inflater.inflate(R.layout.gps_dialog, null)) instead of passing the View that you already inflated, and whose child EditText's you have a reference to, to the dialog, what you are doing is inflating a new version of the gps_dialog.xml and passing that to the dialog. The references that you have are to EditText's that aren't on the screen.

Question:

I am trying to get an EditText.getText().toString() in a fragment working, I have already read all other questions on this issue but cannot find the solution: I have the EditText.getText().toString() in the onClick method for a confirm button after inflating the view, I have checked that the id of the button is correct, but I am not finding the error. In the logcat I can see that the method saveWord which is called after the line in question is called correctly - just the String that is supposed to be filled with the editText is always empty. If I put a hardcoded string on the variable, it works as expected.

Would be very glad if anyone could help! Might be just a silly mistake I am overlooking?

This is my code:

public class BingoAddNewFragment extends Fragment {

private static final String LOG_TAG = BingoDataManager.class.getSimpleName();

View v;

public static final String DEFAULT_EDIT_FRAGMENT_TAG = "editFragmentTag";


private Button mConfirmButton;
EditText mAddWords;

String newWord;

String bWord1 = ""; 
String bWord2 = ""; 
String bWord3 = ""; 
String bWord4= ""; 
String bWord5= ""; 
String bWord6= ""; 
String bWord7= ""; 
String bWord8= ""; 
String bWord9= ""; 
String bWord10= ""; 
String bWord11= ""; 
String bWord12= ""; 
String bWord13= ""; 
String bWord14= ""; 
String bWord15= ""; 
String bWord16= ""; 

String[] bWord = {bWord1, bWord2, bWord3, bWord4, bWord5, bWord6, bWord7, bWord8, bWord9,
        bWord10, bWord11, bWord12, bWord13, bWord14, bWord15, bWord16};


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.add_bingo_fragment, container, false);

    //some other stuff

    mConfirmButton = v.findViewById(R.id.button_confirm);

    mAddWords = v.findViewById(R.id.editText_addWords);

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

            //The next line is not working (everything else seems fine) ->
            newWord = mAddWords.getText().toString();

            Log.d(LOG_TAG, "Begriff: " + newWord + " wird ├╝bergeben");
            saveWord (newWord);

        }
    });

    mSaveButton = v.findViewById(R.id.button_save_bingo);

    mSaveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveBingo();
        }
    });


public String[] saveWord (String newWord) {

    Log.d(LOG_TAG, "Wort: " + newWord + " entgegengenommen.");

    for (int i=0; i<16; i++) {

        Log.d(LOG_TAG,  "i steht bei: " +i);
        if (bWord[i].equals("")) {
            bWord[i] = newWord;
            Log.d(LOG_TAG, "Word als " + (i+1) + ". Begriff gespeichert.");
            break;
        }
    }
    return bWord;
}

And this is an extract of my layout file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorLightBlue">


    <EditText
        android:id="@+id/editText_addWords"
        android:layout_width="206dp"
        android:layout_height="40dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="@string/input_word"
        android:inputType="textPersonName"
        android:textColor="@color/colorDarkBlue"
        android:textColorHint="@drawable/selector"
        android:textSize="12dp"
        app:layout_constraintEnd_toStartOf="@+id/button_confirm"
        app:layout_constraintHorizontal_bias="0.31"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_title" />

Answer:

I found a solution - though I am still not sure why it did not work. I changed the buttons into ImageButtons and suddenly it works perfectly fine.

Question:

I'm adding a text in EditBox with setText code.After I'm changing this text into EditText and I want to get in a String value this text with getText.But this returning null.

My code:

EditText kullanilan = (EditText) findViewById(R.id.edt_kullanilacakSayi);
 gunSayi = Double.toString(izinGun); // gunSayi is string value
  kullanilan.setText(gunSayi);
       String songunSayi=kullanilan.getText().toString();

Answer:

I found a solution.

 kullanilan.addTextChangedListener(new TextWatcher() {
       @Override
       public void beforeTextChanged(CharSequence s, int start, int count, int after) {

       }

       @Override
       public void onTextChanged(CharSequence s, int start, int before, int count) {

       }

       @Override
       public void afterTextChanged(Editable s) {
           songunSayi=kullanilan.getText().toString();
       }
   });
    }

Question:

I've been searching and I don't find the way. The solutions I found doesn't work or I don't know how to implement them.

My Main Activity

public class MainActivity extends AppCompatActivity {



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

        EditText txtDescription = (EditText) findViewById(R.id.nameE);
        final String nameE2 = txtDescription.getText().toString();

        Button bVerify = (Button) findViewById(R.id.verifyB);
        bVerify.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                /** Called when the user clicks the Next button */
                Log.d("EditText", nameE2);
                Intent intent = new Intent(MainActivity.this, ResultActivity.class);
                intent.putExtra(EXTRA_MESSAGE, nameE2);
                startResultActivity(null);
            }
        });
    }

    public void startResultActivity(View view){
        Intent sra = new Intent(this, ResultActivity.class);
        startActivity(sra);

    }
    }

This, already in my code, are the 2 solutions I found everywere, but I don't know how to use them:

 EditText txtDescription = (EditText) findViewById(R.id.nameE);
    String nameE2 = txtDescription.getText().toString();

&

Log.d("EditText", nameE2);
        Intent intent = new Intent(MainActivity.this, ResultActivity.class);
        intent.putExtra(EXTRA_MESSAGE, nameE2);

Inside activity_main, among other things, I've this EditText and this button:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:text="Name"
    android:ems="10"
    android:id="@+id/nameE"
    android:layout_below="@+id/NameTxt"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:editable="false" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/verifyB"
    android:layout_alignParentStart="true"
    android:text="@string/verifyB"
    android:layout_alignParentEnd="true"
    android:layout_below="@+id/nameE"
    android:layout_alignParentLeft="true" />

In the "ractivity" layout I've this PlainText. In this one I want to add the EditText input from the other activity/layout.

<TextView

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello  + nameE2 + . Are you sure you want to accept these terms?"
    android:id="@+id/textView"
    android:textSize="20dp"
    android:textColor="@color/abc_input_method_navigation_guard" />

"nameE2" must be the string of the EditText.

I would love to know how to solve it.

Thanks in advance. If you need additional data, tell me.


Answer:

This seems fine, with a little modification.

bVerify.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        /** Called when the user clicks the Next button */
        Log.d("EditText", nameE2);
        Intent intent = new Intent(MainActivity.this, ResultActivity.class);
        intent.putExtra(EXTRA_MESSAGE, nameE2);
        startResultActivity(null);
    }
});

Here instead of pass null to startResultActivity(), pass the created Intent similar to this:

bVerify.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        final String nameE2 = txtDescription.getText().toString();
        /** Called when the user clicks the Next button */
        Log.d("EditText", nameE2);
        Intent intent = new Intent(MainActivity.this, ResultActivity.class);
        intent.putExtra(EXTRA_MESSAGE, nameE2);
        startResultActivity(intent);
    }
});

And the startResultActivity() method have to look like this:

public void startResultActivity(Intent intent){

    startActivity(intent);

}

EDIT: As I mentioned, you cannot use your variable directly in your layout file.

You have to set it dynamically. You can do that in your ResultActivity's onCreate() method. It have to look similar to this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ractivity); // your second layout file

    TextView textView = (TextView) findViewById(R.id.textView); 
    String stringResult = getIntent().getStringExtra(EXTRA_MESSAGE);
    String textViewText = "Hello "+ stringResult +". Are you sure you want to accept these terms?";
    textView.setText(textViewText);

}

This will work if in your second layout file there is a Textview with textView id.

Question:

I'm new in android programming. I have made an app where i can fill data and app show this data in the table. But I get an error:

Method getText() must be called from the UI Thread, currently inferred thread is worker

in the following lines:

weight.getText() txtDate.getText() txtTime.getText()

in this code:

@Override
    protected Void doInBackground(Void... params) {

        String w_value = weight.getText().toString();
        String wdate = txtDate.getText().toString();
        String wtime = txtTime.getText().toString();

        // inserting data
        sqlcon.open();
        sqlcon.insertData(w_value, wdate, wtime);
        BuildTable();
        return null;
    }

weight - show number (27.6, 5,0)

txtDate - show date (20-09-2016, 12-03-1988)

txtTime - show time (15:16, 1:06)

My insertData method:

public void insertData(String weight, String date) {

   ContentValues cv = new ContentValues();
   cv.put(MyDbHelper.WEIGHT, weight);
   cv.put(MyDbHelper.WEIGHT_DATE, String.valueOf(date));
   cv.put(MyDbHelper.WEIGHT_TIME, new SimpleDateFormat("HH:mm").format(new Date()));
   database.insert(MyDbHelper.TABLE_WEIGHT, null, cv);

}

Answer:

The error is pretty clear, I think. You must call getText from the UI Thread, but you're not -- you're calling it from doInBackground(), which is in a worker thread. That is not allowed. Only the UI thread can access UI elements.

Question:

I'm trying to override getText() method from EditText (which extends TextView). I need to do some checks on who's calling my custom method and if all checks are passed then call the "original" EditText.getText().

The issue resides in the fact that my custom method gets called multiple times until an OOM error gets thrown at me, note that my custom method isn't yet called from nowhere.

This is the code: (the aforementioned checks are not in here, I've just pasted the orignal EditText.getText implementation as a replacement but the issue is still present)

public class CustomEdit extends EditText {


    public CustomEdit(Context context) {
        this(context, null);
    }

    public CustomEdit(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomEdit(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public Editable getText() {

        System.out.println("Should be printed once called...");

        CharSequence text = super.getText();

        if (text == null) {
            return null;
        }
        if (text instanceof Editable) {
            return (Editable) super.getText();
        }
        super.setText(text, BufferType.EDITABLE);
        return (Editable) super.getText();

    }

}

This is my MainActivity:

public class MainActivity extends AppCompatActivity {

    CustomEdit s;

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

        s = findViewById(R.id.newEditText);

    }
}

I expect not to read multiple "Should be printed once called..." at Runtime, at this point I should expect not to see even one instance of it since the method hasn't been yet called.


Answer:

EditText extends from TextView class and TextView class with call getText() method in its constructor. This happens whenever you create any instance of a custom widget that's a direct/indirect subclass of TextView, I guess this is the reason, your custom view's getText() gets invoked, even though it's nowhere invoked in your project code.

If you want to perform some checks and then invoke original getText() method, to get the value from it, then don't override the method in your custom class. Have a normal method in your custom class that has those checks and then calls the original method(to get the value) based on those checks, then you can return value from your normal method.

Question:

I have this code:

void sendMessage(){
    EditText messageText = (EditText) findViewById(R.id.editText3);
    String messageString = messageText.getText().toString();
    LinearLayout chatLayout = (LinearLayout) findViewById(R.id.chatView);
    TextView chatMessage = new TextView(this);
    chatMessage.setText(messageString);
    chatLayout.addView(chatMessage);
    messageText.setText("");
    scrollChatDown();
    /*
    int arraySize = messages.size();
    messages.set(arraySize + 1, chatMessage);
    */
}

When I call the function sendMessage(); by a button, it gives an empty TextView, when I call the function again, it gives me a TextView with the text.

Output

I did what jiotman said but it didn't work, now I have this

void sendMessage(){
    TextView chatMessage = new TextView(this);
    EditText messageText = (EditText) findViewById(R.id.editText3);
    String messageString = messageText.getText().toString();
    LinearLayout chatLayout = (LinearLayout) findViewById(R.id.chatView);
    chatLayout.addView(chatMessage);
    chatMessage.setText(messageString);
    messageText.setText("");
    scrollChatDown();
    /*
    int arraySize = messages.size();
    messages.set(arraySize + 1, chatMessage);
    */
}

Answer:

As I see, you`r trying to implement kind of list with item population.

I`d use bubble list view for this purpose, here is a simple tutorials how to do it.

http://javapapers.com/android/android-chat-bubble/

http://blog.booleanbites.com/2012/12/android-listview-with-speech-bubble.html

Question:

I have a small Android Studio app to test the handling of keyboard inputs. It has an EditText field for a name, and a second EditText field for a decimal number. I am using setOnEditorActionListener to get the user input. I then store the entries in a string and double in a separate public class then attempt to display them in a TextView field when a button is clicked. I am concerned to ensure that I've actually definitely got the data in (so it can be used later by other activities).

In the public class, I initialize the string to "****" and the double to 0.0. But when I click the button to display the entered text, the four stars disappear and the field goes blank.

I haven't even tried displaying the entered number because the name text input and display are not working.

What am I doing wrong please? Any help would be much appreciated. Code follows.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_vertical_margin"
            android:paddingBottom="@dimen/activity_vertical_margin"
            tools:context=".MainActivity">

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:hint="Name"
    android:ems="10"
    android:id="@+id/textin"
    android:layout_marginTop="63dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:imeOptions="actionNext"/>

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="numberDecimal"
    android:hint= "Number"
    android:ems="10"
    android:id="@+id/numberin"
    android:layout_below="@+id/textin"
    android:layout_centerHorizontal="true"
    android:imeOptions="actionDone"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="echo"
    android:id="@+id/echo"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button"
    android:layout_below="@+id/echo"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="42dp"/>

</RelativeLayout>

MainActivity.java

package com.example.owner.keyboardinput;

//imports here

public class MainActivity extends AppCompatActivity
{

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

    final TextView echo = (TextView) findViewById(R.id.echo);
    final Button button = (Button) findViewById(R.id.button);

    final EditText textin = (EditText) findViewById(R.id.textin);
    textin.setOnEditorActionListener(new TextView.OnEditorActionListener()
    {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent            event)
        {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_NEXT) {
                String inputText1 = textin.getText().toString();
                Common.str = inputText1;  // Store in common public class
                echo.setText(Common.str); // But input doesn't appear!
            }
            return handled;
        }
    });

    final EditText numberin = (EditText) findViewById(R.id.numberin);
    textin.setOnEditorActionListener(new TextView.OnEditorActionListener()
    {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
        {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                String inputText2 = numberin.getText().toString();
                echo.setText(inputText2);
                //Common.dbl = Double.valueOf(inputText);

                InputMethodManager inputManager = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
                handled = true;
            }
            return handled;
        }
    });

    button.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            echo.setText(Common.str);  // Field goes blank!
        }
    });
}

Common.java

package com.example.owner.keyboardinput;

/**
 * Created by Owner on 13/11/2015.
 */
public class Common
{
    public static String str = "****";
    public static double dbl = 0.0;
}

Answer:

You're calling setOnEditorActionListener() on the textin TextView twice. From your code, it looks like the second call should be on numberin.

...
final EditText numberin = (EditText) findViewById(R.id.numberin);
numberin.setOnEditorActionListener(new TextView.OnEditorActionListener()
...

Question:

I'm trying to make an android app which will show a Toast on button click. That Toast contains the number entered by the user in edittext field. The problem is that i am entering text to edittext(Numeric) field and on button click, Toast isn't showing the text entered by me. Toast is completely blank. Here is my code:-

Activity.java

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

public class login extends AppCompatActivity {

    String username, password;
    Button payNGO, payGO;
    EditText usernameField, passwordField;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        setContentView(R.layout.activity_login);

        payNGO = (Button) findViewById(R.id.payngo);
        payGO = (Button) findViewById(R.id.paygo);

        usernameField = (EditText) findViewById(R.id.forno);
        passwordField = (EditText) findViewById(R.id.dob);

        username = usernameField.getText().toString();
        password = passwordField.getText().toString();


        payNGO.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(login.this, username, Toast.LENGTH_LONG).show();
            }
        });



    }
}

Activity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".login"
    android:background="@drawable/back">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="150dip"
        android:layout_height="150dip"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/forno"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.438"
        app:srcCompat="@drawable/ico" />

    <EditText
        android:id="@+id/forno"
        android:layout_width="match_parent"
        android:layout_height="40dip"
        android:layout_marginBottom="20dp"
        android:layout_marginEnd="30dip"
        android:layout_marginStart="30dip"
        android:background="@drawable/rect_back"
        android:ems="10"
        android:hint="Number"
        android:inputType="number"
        android:paddingEnd="10dp"
        android:paddingStart="10dp"
        app:layout_constraintBottom_toTopOf="@+id/dob"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.562"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/dob"
        android:layout_width="match_parent"
        android:layout_height="40dip"
        android:layout_marginBottom="124dp"
        android:layout_marginEnd="30dip"
        android:layout_marginStart="30dip"
        android:background="@drawable/rect_back"
        android:ems="10"
        android:hint="Date of Birth"
        android:inputType="numberPassword"
        android:paddingEnd="10dp"
        android:paddingStart="10dp"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.562"
        app:layout_constraintStart_toStartOf="parent" />

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="92dp"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent">

        <Button
            android:id="@+id/payngo"
            android:layout_width="wrap_content"
            android:layout_height="40dip"
            android:layout_marginEnd="20dip"
            android:layout_marginStart="15dip"
            android:layout_weight="1"
            android:background="@drawable/rect_back_button"
            android:text="Pay (NGO)"
            tools:layout_editor_absoluteX="204dp"
            tools:layout_editor_absoluteY="440dp" />

        <Button
            android:id="@+id/paygo"
            android:layout_width="wrap_content"
            android:layout_height="40dip"
            android:layout_marginEnd="15dip"
            android:layout_marginStart="20dip"
            android:layout_weight="1"
            android:background="@drawable/rect_back_button"
            android:text="Pay (GO)"
            tools:layout_editor_absoluteX="92dp"
            tools:layout_editor_absoluteY="440dp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:background="@drawable/rect_back_text"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="50dip"
            android:layout_weight="1"
            android:text="@string/linef"
            android:textAlignment="textEnd"
            android:textColor="#fff"
            android:textSize="20sp"
            tools:layout_editor_absoluteX="30dp"
            tools:layout_editor_absoluteY="505dp" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:scaleType="fitCenter"

            app:srcCompat="@drawable/heart"
            tools:ignore="VectorDrawableCompat" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="50dip"
            android:layout_weight="1"
            android:text="@string/linee"
            android:textColor="#fff"
            android:textSize="20sp"
            tools:layout_editor_absoluteX="171dp"
            tools:layout_editor_absoluteY="505dp" />
    </LinearLayout>

</android.support.constraint.ConstraintLayout>

Answer:

Since you are getting the value in onCreate which will be executed even before you enter anything, your Toast shows blank data.

Move the getText() methods to onClick to achieve expected result as follows:

    payNGO.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            username = usernameField.getText().toString();
            password = passwordField.getText().toString();
            Toast.makeText(login.this, username, Toast.LENGTH_LONG).show();
        }

    });

Question:

I have a fairly simple question for you, regarding a getText().toString() method I'm using in an if statement.

Essentially, I'm asking the user a question. If they input the correct answer in the appropriate EditText, they move on to the next question. If not, they lose life. If their life is reduced to 0, they are sent back to the beginning of the game. If not, they must repeat the question. The problem I'm having while testing this is that after entering the correct answer, in this case "Atlantic", the method is executing as though the answer is wrong. Can anyone help with this?

PS I am aware that the Else If is redundant, it's just there for clarification purposes.

The code:

    answerButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (answerText.getText().toString() == "Atlantic") {
                KrakonQ2();
            }
            else if (answerText.getText().toString() != "Atlantic")
            {
                thePlayer.setPlayerHP(thePlayer.getPlayerHP() - 20);

                if (thePlayer.getPlayerHP() <= 0)
                {
                    thePlayer.setPlayerPos(0);
                    setupControls();
                    RoomText.setText(thedungeon[thePlayer.getPlayerPos()].getName());
                    setupDirectionButtons();
                    thePlayer.setPlayerHP(100);

                }
                else
                {
                    KrakonQ1();
                }


            }

        }
    });

Answer:

Yeah, you need to use String.equals()

if (answerText.getText().toString().equals("Atlantic")) { 
       KrakonQ2(); 
   } 

== compares objects to see if they are the same.

Question:

The Toast keeps saying access denied, even if i fill in the right pin.

I need to lock users into an kiosk-mode app, and only with the right pin they will have access to the settings and the exit option.

            public void onClick(View v) {

            AlertDialog.Builder alert = new AlertDialog.Builder(FullscreenActivity.this);
            alert.setTitle("PIN:");
            //alert.setMessage("Message");

            final EditText pinEntry = new EditText(FullscreenActivity.this);
            alert.setView(pinEntry);
            alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    String pin = pinEntry.getText().toString().trim();
                    String secret = "0000";
                    if (pin == secret){
                        Toast.makeText(getApplicationContext(),"Access Approved", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        Toast.makeText(getApplicationContext(),"Access Denied", Toast.LENGTH_SHORT).show();
                    }
                    Toast.makeText(getApplicationContext(),pin, Toast.LENGTH_SHORT).show();
                }
            });

            alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                }
            });
            alert.show();
        }
    });

Answer:

== tests for reference equality.

.equals() tests for value equality.

Question:

I am working on an notes app for android. I am trying to save the text the user wrote to EditText into a variable inputText . But the variable is always "". I am really confused. Any ideas? (The problem is probbably in Setphase2 method.)

package vitosoft.notes;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

    final int[] phase = {1};
    final String[] text_encode = {""};
    final Button r_button = findViewById(R.id.rightButton);
    final Button l_button = findViewById(R.id.leftButton);
    final EditText input = findViewById(R.id.editText);
    final TextView task = findViewById(R.id.task);

    r_button.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("SetTextI18n")
        public void onClick(View v) {
            if (phase[0] == 1) {
                phase[0] = 2;
                text_encode[0] = Setphase2(r_button, l_button, task, input);
            }
        }
    });

    l_button.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("SetTextI18n")
        public void onClick(View v) {
            if (phase[0] == 2) {
                phase[0] = 1;
                Setphase1(text_encode[0], r_button, l_button, task, input);

            }
        }
    });
    }

public String Setphase2(Button r,Button l,TextView t,EditText i) {
    i.setText("");
    r.setText(R.string.upload);
    l.setText(R.string.edit);
    t.setText(R.string.key_task);
    String inputText = i.getText().toString();
    Log.d("UserText", "Entry text is:" + inputText);
    i.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
    return inputText;
}
public void Setphase1 (String original, Button r,Button l,TextView t,EditText i){
    i.setText(original);
    r.setText(R.string.encode);
    l.setText(R.string.decode);
    t.setText(R.string.entry_task);
    i.setInputType(InputType.TYPE_CLASS_TEXT);

}
}

Answer:

Android edittext.getText().toString() is always empty.. Because you assigning it as empty.

public String Setphase2(Button r,Button l,TextView t,EditText i) {
    i.setText(""); // See this line**************
    r.setText(R.string.upload);
    l.setText(R.string.edit);
    t.setText(R.string.key_task);
    String inputText = i.getText().toString();
    Log.d("UserText", "Entry text is:" + inputText);
    i.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
    return inputText;
}

Remove the following line in the above method.

i.setText("");