Getting what the user typed — Android #7

icons from icons8.com as usual!

A quick tutorial today — how to let the user type something in the app and to do something with it.

Open a new project with an Empty Activity and open the default activity_main layout file:

activity_main.xml

A simple way to get the user to enter text is to use an EditText object; you’ll find it in the Palette section:

EditTexts in the Palette

An EditText is basically what it says on the tin — a text object that the user can edit. As you can see, there are a good few different types of EditText — Plain Text, Password, E-mail etc. These are handy variations provided in Android that have different behaviour. e.g. the keyboard that the user uses to enter text may be different depending what EditText is used. A Phone EditText will show a numeric keyboard to the user, a Plain Text will show the standard alphanumeric one.

Let’s try them out, so:

  • Delete the existing “Hello World” TextView
  • Drag out a LinearLayout (vertical)
  • Drag a Plain Text into the LinearLayout
  • Drag a Phone into the LinearLayout

So the Component Tree looks like this:

and the Design looks like this:

after adding two EditTexts.

Note the Plain Text defaults to “Name” and the Phone is blank. Let’s change their colors so the user can see them easier. Use the background property. If you can’t see it in the Properties panel, hit the little button at the top that looks like two arrows going in different directions, and you’ll see all available properties:

Then scroll down until you see background. Hit the little button with the three dots, to the right, to open the color selection dialog:

On the left-hand side, hit Color, choose one and hit OK:

The background of the EditText should have changed:

Change the Name EditText’s color aswell, and also give it a layout_marginBottom of 5sp:

so there’s some space between the two:

The Plain Text defaulted to “Name”, but we want the user to enter the text, not us. So delete “Name” from the text property and instead type it into “hint”. The hint will appear in the same place, but will disappear when the user starts typing:

Do the same for the Phone EditText:

If you remember from earlier guides, we use the ID property to reference objects in the layout file with code in the Java file. Let’s change the IDs of the two EditText to something more meaningful. For the Name:

and the Phone:

We’ll use those IDs shortly. First however, run the app — the two EditTexts should be on screen and when you tap on them, the keyboard should pop up. For the Name, you should see this:

and the Phone:

See the different keyboards? Excellent.

Before we get to the code, let’s add two more objects:

  • A Button to allow the user to “Submit” their details
  • A blank TextView to display them back to the user — so we can show how to get and use the entered values

So, add a Button to the LinearLayout, change it’s size / color / text etc as desired, such that it looks like this:

Note that I gave it a layout_marginTop of 5sp to give it a little room from the EditText above it:

We also need to add an “onClick” property to the Button — so when the user hits it, we can handle it. You can change the XML code, or just use the onClick property, here I call it onSubmit:

This is a method that doesn’t exist yet, we’ll do that in a minute.

Now add a TextView underneath:

and set it’s alignment to centre and change its textSize to 24sp, but leave it blank by clearing its text value:

We can leave the ID as is.

Ok, all that setup is now done. That was a lot of screenshots for what’s actually quite simple, we may aswell be clear on all stages!

Now open the MainActivity.java file, there shouldn’t be anything there apart from the standard onCreate method:

Let’s add the onSubmit method that we hooked up to the Button a short time ago:

//when user hits the submit button
public void onSubmit(View v){
//get references to the objects in the layout
TextView myTextView = (TextView) findViewById(R.id.textView);
EditText nameEditText = (EditText) findViewById(R.id.nameID);
EditText phoneEditText = (EditText) findViewById(R.id.phoneID);
//set the text view to the name and the phone number entered by the user
myTextView.setText(nameEditText.getText() + " " + phoneEditText.getText());
}

These:

TextView myTextView = (TextView) findViewById(R.id.textView);
EditText nameEditText = (EditText) findViewById(R.id.nameID);
EditText phoneEditText = (EditText) findViewById(R.id.phoneID);

create three new variables, referencing the objects we created in the layout, using their IDs.

myTextView.setText(nameEditText.getText() + " " + phoneEditText.getText());

sets the text of the TextView. Broken down further:

nameEditText.getText()

uses the getText() method to get the text that the user entered, likewise with:

phoneEditText.getText());

The

+ " " +

in the middle adds a blank space, so the output won’t look something like Andy12345. We use the + operator to concatenate Strings together.

Run the app! Type some stuff into the two EditTexts and hit Submit:

It works! The keyboard is still there though when I hit Submit, it’d be nice if it went off screen.

Add this to the bottom of the onSubmit method:

InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);if(imm.isAcceptingText()) { // verify if the soft keyboard is open
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}

so the whole method is:

//when user hits the submit button
public void onSubmit(View v){
//get references to the objects in the layout
TextView myTextView = (TextView) findViewById(R.id.textView);
EditText nameEditText = (EditText) findViewById(R.id.nameID);
EditText phoneEditText = (EditText) findViewById(R.id.phoneID);
//set the text view to the name and the phone number entered by the user
myTextView.setText(nameEditText.getText() + " " + phoneEditText.getText());
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); if(imm.isAcceptingText()) { // verify if the soft keyboard is open
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}

Now, run the app again and you’ll see that the keyboard goes away when you hit submit. Note that I didn’t remember how to do this — so I just googled “Android dismiss keyboard”. I found a link on Stackoverflow, read a few of the answers and tried them out. Sometimes it’s good to read all the official documentation and sometimes it’s good just to google for an answer, that’s what Stackoverflow is there for!

One more thing before we go — what if the fields are blank when the user hits Submit? Let’s put in some code to check if the fields are blank, if they are we’ll tell the user to sort it out!

So, replace:

myTextView.setText(nameEditText.getText() + " " + phoneEditText.getText());

with:

if (TextUtils.isEmpty(nameEditText.getText()) || TextUtils.isEmpty(phoneEditText.getText())){
myTextView.setText("Fill in both fields!");
}else{
myTextView.setText(nameEditText.getText() + " " + phoneEditText.getText());
}

What’s going on? There’s a few ways of checking whether a String is empty — one way is TextUtils.isEmpty(String to check)

So we check if the text in the Name EditText is empty:

if (TextUtils.isEmpty(nameEditText.getText())

and likewise with

TextUtils.isEmpty(phoneEditText.getText())

The

||

in the middle is the Logical Operator OR. if (A || B) basically means that if A OR B are true — i.e. if either EditTexts are empty, then show “Fill in both fields!” on screen.

Note aswell the opening bracket ( and closing bracket ) around the line, we need this. Ok, the code should look like this:

package com.example.whatever.myapplication;import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
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);
}
//when user hits the submit button
public void onSubmit(View v){
//get references to the objects in the layout
TextView myTextView = (TextView) findViewById(R.id.textView);
EditText nameEditText = (EditText) findViewById(R.id.nameID);
EditText phoneEditText = (EditText) findViewById(R.id.phoneID);
//set the text view to the name and the phone number entered by the userif (TextUtils.isEmpty(nameEditText.getText()) || TextUtils.isEmpty(phoneEditText.getText())){
myTextView.setText("Fill in both fields!");
}else{
myTextView.setText(nameEditText.getText() + " " + phoneEditText.getText());
}
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); if(imm.isAcceptingText()) { // verify if the soft keyboard is open
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
}

Run the app and hit Submit before you type anything in:

Likewise, if you fill in one field and hit Submit:

Done! I hope that all made sense! Any issues or comments, just let me know below.

If you liked the article, please hit the little heart button below! Thanks! Andy.

Creator of Boxapopa, the iOS game for young kids with zero ads, just fun! https://apps.apple.com/ie/app/boxapopa/id1550536188