Andriod programming – Posts 8: Intent – Switching between screens

Too 7 Basic previous post, given the relative stability that you grasp how interface design as well as start events button. And I also believe that if you do your track series that intends to further – means studious than others are very inquisitive child groping her home is how clickable button that can open another screen. Today all of us will do that through a simple app – Register login.

[qads]

The principle of this application briefly as follows: You will have to log into a system by entering your username and password. If true, the move to a new screen to start using the system. If users have an account yet, you can register for an account, after registering, return the login screen and automatically fill login name box. Thus we have the following application diagram:

android-login-form-1

Already, now you open Android Studio and creates a new Project. Note a bit is at the present time, Android Studio has allowed us to create a Login Activity, however I did not use it because it will automatically generate lots of code, to explain all those that code for you, it takes a lot of time and will not focus on this post. So ask yourself the code of their research offline. Here I have created from the Empty Activity.

When creating your Project is named Activity LoginActivity, file xml là activity_login, Title là Login. The code you need not temporarily offline java. Now let's create notes 2 The remaining activity was.
First create Activity Register (register). The right-click your package, selected new -> Activity -> Empty Activty

android-create-activity

Next to your name and file name Interface Activity, often automatically put Athens under the name Activity.

android-create-activity-1

Note you uncheck the box Launcher Activity nhé. If integrated into the Activity will open up when you open the app.
Similarly, we create notes Main Activity – Login interface where success.

Now start designing interfaces and Java code.

First you set the variables in the file /res/values/string.xml

<resources>
    <string name="app_name">TUT8Intent</string>

    <!-- Strings related to login -->
    <string name="login">Login</string>
    <string name="user_name">User name</string>
    <string name="password">Password</string>
    <string name="confirm_password">Confirm Password</string>

    <string name="register">Register</string>

    <string name="action_sign_in_short">Sign in</string>
    <string name="error_field_required">This field is required</string>
    <string name="error_password_not_match">Password not match</string>

    <string name="login_success">Hi, {0}. You login with password is {1}</string>
</resources>

We add the library to use TextInputLayout design combined with EditText by opening the file build.gradle and edit dependencies to:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.0.0'
    compile 'com.android.support:design:24.0.0'
}

In all of the interfaces on, easy to see that we can use for convenient LinearLayout. Here is the code interface for LoginActivity.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp">

    <!-- Login progress -->
    <ProgressBar
        android:id="@+id/login_progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:visibility="gone" />

    <ScrollView
        android:id="@+id/login_form"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <EditText
                    android:id="@+id/editUserName"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/user_name"
                    android:singleLine="true" />

            </android.support.design.widget.TextInputLayout>

            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <EditText
                    android:id="@+id/editPassword"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/password"
                    android:inputType="textPassword"
                    android:singleLine="true" />

            </android.support.design.widget.TextInputLayout>

            <Button
                android:id="@+id/btnLogin"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="16dp"
                android:text="@string/login" />

        </LinearLayout>
    </ScrollView>
</LinearLayout>

This section alone will not explain anything more except object ProgressBar This is displayed as an object wait, it will spin (or horizontal, but here is round) to indicate the user's wait we are handling jobs.
Properties android:visibility worth gone will make it hidden away, when you want it to show up, then set the value for it is visible

Login Activity processing java code as follows:

package com.nguyenvanquan7826.tut8intent;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String KEY_USER_TO_MAIN = "KEY_USER_TO_MAIN";
    public static final String KEY_PASSWORD_TO_MAIN = "KEY_PASSWORD_TO_MAIN";

    public static final String KEY_USER_FROM_REGISTER = "KEY_USER_FROM_REGISTER";

    public static final int REQUEST_CODE_REGISTER = 1;

    private Context context;

    private EditText editUserName;
    private EditText editPassword;

    private ProgressBar progressBar;

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

        context = this;

        connectView();
    }

    private void connectView() {
        editUserName = (EditText) findViewById(R.id.editUserName);
        editPassword = (EditText) findViewById(R.id.editPassword);

        progressBar = (ProgressBar) findViewById(R.id.progressLogin);

        findViewById(R.id.btnLogin).setOnClickListener(this);
        findViewById(R.id.btnRegister).setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.btnLogin:
                login();
                break;
            case R.id.btnRegister:
                register();
                break;
        }
    }

    private void login() {
        boolean error = false;

        showProgress(true);
        // when process we must have sometime

        // get data
        String userName = editUserName.getText().toString().trim();
        String password = editPassword.getText().toString().trim();

        // password empty
        if (TextUtils.isEmpty(password)) {
            editPassword.requestFocus();
            editPassword.setError(context.getResources().getString(R.string.error_field_required));
            error = true;
        }

        // username empty
        if (TextUtils.isEmpty(userName)) {
            editUserName.requestFocus();
            editUserName.setError(context.getResources().getString(R.string.error_field_required));
            error = true;
        }

        // all data is ok
        showProgress(false);

        if (!error) {
            // create intent to show Main Activity
            Intent intent = new Intent(context, MainActivity.class);

            // send data if need
            intent.putExtra(KEY_USER_TO_MAIN, userName);
            intent.putExtra(KEY_PASSWORD_TO_MAIN, password);

            // start Main Activity
            startActivity(intent);
        }
    }

    private void register() {
        Intent intent = new Intent(context, RegisterActivity.class);
        startActivityForResult(intent, REQUEST_CODE_REGISTER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_REGISTER && resultCode == Activity.RESULT_OK) {
            String userName = data.getStringExtra(KEY_USER_FROM_REGISTER);
            editUserName.setText(userName);
            editPassword.requestFocus();
        }
    }

    private void showProgress(boolean isShow) {
        progressBar.setVisibility(isShow ? View.VISIBLE : View.GONE);
        findViewById(R.id.login_form).setVisibility(!isShow ? View.VISIBLE : View.GONE);
    }
}

In this code you need to note:
– At the login function, we have known 2 time show progress(true); and show progress(false); ie when initial treatment and will take some time to show up progress, then finished processing the hides. But because of our work so fast that you will not see the pop-up progress.

  • After all the data is OK, then start taking MainActivity intent to call out. Here your attention:
    // create intent to show Main Activity
    Intent intent = new Intent(context, MainActivity.class);
    
    // send data if need
    intent.putExtra(KEY_USER_TO_MAIN, userName);
    intent.putExtra(KEY_PASSWORD_TO_MAIN, password);
    
    // start Main Activity
    startActivity(intent);
    

    +/ The first line is the way we create Intent to move from Activity to another Activity. In which context is the context – the current Activity, MainActivity.class is we need to move to Activity.
    +/ The first line 2,3 we use intent to put some data into, here is given a username and password to MainActivity through 1 Keyword is KEY_USER_TO_MAIN and KEY_PASSWORD_TO_MAIN, it is 2 constant, it is also the key – Key to the other side we can get exactly where userName, where is password.
    +/ The last line is to start the switch to a new Activity.

  • You see a big difference that I have set Error to EditText EditText UserName and Password. When the error we have beautiful interface as follows:

error-for-edittext

  • When the call register, their intent to create a similar, however the recall process you after registration is completed, we need to fill in your name just registered on EditText UserName, so I had to call how after the end RegisterActivity will receive the returned result is that through the command UserName:
    startActivityForResult(intent, REQUEST_CODE_REGISTER);
    => Start Packages – start activity, ForResult is allowed to return results. Here, REQUEST_CODE_REGISTER is an integer, it is also the key for us to get to know if the results returned are paid from public Activity, because in practice, 1 Activty can call and much more Activity Activity also can return the result to the original Activty.

  • To receive electronic data returned Register, we must override function onActivityResult – when the returned results Activity. Here:
    requestCode The main distinction is the code when we call public Activity, to get the correct result of RegisterAcitivty, we need to check it to see matches REQUEST_CODE_REGISTER not.
    resultCode confirmation code view RegisterAcitivty accept returns results not, if it is RESULT_OK.
    Then we get the results through Intent data.

At this point you absolutely can run applications, but in MainActivity and RegisterActivity us nothing. So now again.

Interface code main activity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.nguyenvanquan7826.tut8intent.MainActivity">

    <TextView
        android:id="@+id/tvMain"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Code java activity main:

package com.nguyenvanquan7826.tut8intent;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private Context context;

    private TextView tvMain;

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

        context = this;

        connectView();
        getData();
    }

    private void connectView() {
        tvMain = (TextView) findViewById(R.id.tvMain);
    }

    private void getData() {
        String userName = getIntent().getStringExtra(LoginActivity.KEY_USER_TO_MAIN);
        String password = getIntent().getStringExtra(LoginActivity.KEY_PASSWORD_TO_MAIN);

        String helloText = context.getResources().getString(R.string.login_success);
        helloText = completeText(helloText, new String[]{userName, password});
        tvMain.setText(helloText);
    }

    private String completeText(String source, String[] items) {
        for (int i = 0; i < items.length; i++) {
            source = source.replace("{" + i + "}", items[i]);
        }
        return source;
    }
}

Above, we take the data with the command getIntent().getStringExtra, take any value, it must transmit the corresponding KEY and exactly the same as when we were sent. Now you note why I put KEY_USER_TO_MAIN and constants KEY_PASSWORD_TO_MAIN? Lest confusion, in many places, If the string you pass as a guy, you have to remember it's KEY and write correctly in many places it. When we put every name, every day-is ok, not worrying about the wrong thing boils.

Continuing with the Register offline Last Activity. It is similar to Login so you only care about how to send the data back to the whiff LoginActivity.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp">

    <!-- Login progress -->
    <ProgressBar
        android:id="@+id/progressLogin"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:visibility="gone" />

    <ScrollView
        android:id="@+id/login_form"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <EditText
                    android:id="@+id/editUserName"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/user_name"
                    android:singleLine="true" />

            </android.support.design.widget.TextInputLayout>

            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <EditText
                    android:id="@+id/editPassword"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/password"
                    android:inputType="textPassword"
                    android:singleLine="true" />

            </android.support.design.widget.TextInputLayout>

            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <EditText
                    android:id="@+id/editRePassword"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/confirm_password"
                    android:inputType="textPassword"
                    android:singleLine="true" />

            </android.support.design.widget.TextInputLayout>

            <Button
                android:id="@+id/btnRegister"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="16dp"
                android:text="@string/register" />

        </LinearLayout>
    </ScrollView>
</LinearLayout>

Java code of RegisterActivity

package com.nguyenvanquan7826.tut8intent;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
    private Context context;

    private EditText editUserName;
    private EditText editPassword;
    private EditText editRePassword;

    private ProgressBar progressBar;

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

        context = this;

        connectView();
    }

    private void connectView() {
        editUserName = (EditText) findViewById(R.id.editUserName);
        editPassword = (EditText) findViewById(R.id.editPassword);
        editRePassword = (EditText) findViewById(R.id.editRePassword);

        progressBar = (ProgressBar) findViewById(R.id.progressLogin);

        findViewById(R.id.btnRegister).setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.btnRegister:
                register();
                break;
        }
    }

    private void register() {
        boolean error = false;

        showProgress(true);
        // when process we must have sometime

        // get data
        String userName = editUserName.getText().toString().trim();
        String password = editPassword.getText().toString().trim();
        String rePassword = editRePassword.getText().toString().trim();

        // password empty
        if (TextUtils.isEmpty(rePassword)) {
            editRePassword.requestFocus();
            editRePassword.setError(context.getResources().getString(R.string.error_field_required));
            error = true;
        }

        // password empty
        if (TextUtils.isEmpty(password)) {
            editPassword.requestFocus();
            editPassword.setError(context.getResources().getString(R.string.error_field_required));
            error = true;
        }

        // username empty
        if (TextUtils.isEmpty(userName)) {
            editUserName.requestFocus();
            editUserName.setError(context.getResources().getString(R.string.error_field_required));
            error = true;
        }

        if (!password.equals(rePassword)) {
            editRePassword.requestFocus();
            editRePassword.setError(context.getResources().getString(R.string.error_password_not_match));
            error = true;
        }

        // all data is ok
        showProgress(false);

        if (!error) {
            // create intent to send data back Login Activity
            Intent intent = new Intent();

            // send data
            intent.putExtra(LoginActivity.KEY_USER_FROM_REGISTER, userName);

            setResult(RESULT_OK, intent);
            finish();
        }
    }

    private void showProgress(boolean isShow) {
        progressBar.setVisibility(isShow ? View.VISIBLE : View.GONE);
        findViewById(R.id.login_form).setVisibility(!isShow ? View.VISIBLE : View.GONE);
    }
}