By GokiSoft.com| 11:51 13/03/2021|
Android

[Share Code] Tìm hiểu về Activity - Truyền dữ liệu giữa Activity - SharedPreferences - Lập trình Android

#UserInforActivity.java


package gokisoft.j2010g;

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

public class UserInforActivity extends AppCompatActivity {
    TextView txtFullname, txtEmail, txtAddress;

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

        //Mapping
        txtFullname = findViewById(R.id.aui_txt_fullname);
        txtEmail = findViewById(R.id.aui_txt_email);
        txtAddress = findViewById(R.id.aui_txt_address);

        //Doc du lieu gui tu LoginActivity
        String fullname = getIntent().getStringExtra("fullname");
        String email = getIntent().getStringExtra("email");
        String address = getIntent().getStringExtra("address");

        txtFullname.setText(fullname);
        txtEmail.setText(email);
        txtAddress.setText(address);
    }
}


#TestActivity.java


package gokisoft.j2010g;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class TestActivity extends AppCompatActivity {

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


#RegisterActivity.java


package gokisoft.j2010g;

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

public class RegisterActivity extends AppCompatActivity {
    EditText txtFullname, txtEmail, txtAddress, txtPwd, txtConfirmPwd;
    Button btnRegister, btnBack;

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

        //Mapping
        txtFullname = findViewById(R.id.ar_txt_fullname);
        txtEmail = findViewById(R.id.ar_txt_email);
        txtAddress = findViewById(R.id.ar_txt_address);
        txtPwd = findViewById(R.id.ar_txt_password);
        txtConfirmPwd = findViewById(R.id.ar_txt_confirm_pwd);

        btnRegister = findViewById(R.id.ar_btn_register);
        btnBack = findViewById(R.id.ar_btn_back);

        //Dang ky lang nghe su kien
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                register();
            }
        });

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                back();
            }
        });
    }

    private void back() {
        finish();
    }

    private void register() {
        String fullname = txtFullname.getText().toString();
        String email = txtEmail.getText().toString();
        String address = txtAddress.getText().toString();
        String pwd = txtPwd.getText().toString();
        String confirmPwd = txtConfirmPwd.getText().toString();

        if(!pwd.equals(confirmPwd)) {
            Toast.makeText(this, "Mat khau khong khop!!!", Toast.LENGTH_SHORT).show();
        } else {
            //Dang ky thang cong
            Intent i = new Intent();
            i.putExtra("fullname", fullname);
            i.putExtra("email", email);
            i.putExtra("address", address);
            i.putExtra("password", pwd);
            setResult(LoginActivity.CODE_REGISTER, i);

            //Save du lieu => SharedPreferences
            SharedPreferences sharedPreferences = getSharedPreferences("J2010G", MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();

            //Luu
            editor.putString("fullname", fullname);
            editor.putString("email", email);
            editor.putString("address", address);
            editor.putString("password", pwd);

            editor.commit();//Luu thay doi trong SharedPrerences.

            finish();
        }
    }
}


#User.java


package gokisoft.j2010g.model;

/**
 * Created by Diep.Tran on 3/13/21.
 */

public class User {
    String fullname, email, address, pwd;

    public User() {
    }

    public User(String fullname, String email, String address, String pwd) {
        this.fullname = fullname;
        this.email = email;
        this.address = address;
        this.pwd = pwd;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "fullname='" + fullname + '\'' +
                ", email='" + email + '\'' +
                ", address='" + address + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}


#MainActivity.java


package gokisoft.j2010g;

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

public class MainActivity extends AppCompatActivity {
    //Mapping object trong XML sang Java
    EditText edEmail, edPassword;
    Button btnSave, btnReset, btnStart;

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

        //Mapping object java & component trong xml
        edEmail = findViewById(R.id.am_ed_email);
        edPassword = findViewById(R.id.am_ed_password);
        btnSave = findViewById(R.id.am_btn_save);
        btnReset = findViewById(R.id.am_btn_reset);
        btnStart = findViewById(R.id.am_btn_start);

        //Bat su kien khi nguoi dung click vao button save & reset
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //noi xu ly code -> khi click vao button save
                String email = edEmail.getText().toString();
                String pwd = edPassword.getText().toString();

                Log.d("MainActivity", email);
                Log.d(MainActivity.class.getName(), pwd);

                //Gia su neu email: aptech@com & pwd: 123 => show message: Login success!
                //Show message: Login failed.
                if(email.equals("aptech@com") && pwd.equals("123")) {
                    //login success
                    Toast.makeText(MainActivity.this, "Login success", Toast.LENGTH_SHORT).show();
                } else {
                    //login failed
                    Toast.makeText(MainActivity.this, "Login failed", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //noi xu ly code -> khi click vao button reset
                edEmail.setText("");
                edPassword.setText("");
            }
        });

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent in = new Intent(MainActivity.this, TestActivity.class);
                startActivity(in);
            }
        });
    }
}


#LoginActivity.java


package gokisoft.j2010g;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import gokisoft.j2010g.model.User;

public class LoginActivity extends AppCompatActivity {
    public static int CODE_REGISTER = 101;

    EditText txtEmail, txtPwd;
    Button btnSave, btnRegister, btnShow, btnLoadData;
    TextView viewNotify;

    User user = null;

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

        //Mapping item trong layout -> code java
        txtEmail = findViewById(R.id.al_txt_email);
        txtPwd = findViewById(R.id.al_txt_password);
        btnSave = findViewById(R.id.al_btn_login);
        btnRegister = findViewById(R.id.al_btn_register);
        btnShow = findViewById(R.id.al_btn_show);
        btnLoadData = findViewById(R.id.al_btn_load_data);
        viewNotify = findViewById(R.id.al_view_notify);

        //Dang ky lang nghe su kien khi click btn login & register
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkLogin();
            }
        });

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showRegisterActivity();
            }
        });

        btnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showUserInfor();
            }
        });

        btnLoadData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences sharedPreferences = getSharedPreferences("J2010G", MODE_PRIVATE);
                //Doc noi dung du lieu
                String fullname = sharedPreferences.getString("fullname", "");
                String email = sharedPreferences.getString("email", "");
                String address = sharedPreferences.getString("address", "");
                String password = sharedPreferences.getString("password", "");

                user = new User(fullname, email, address, password);

                btnLoadData.setVisibility(View.GONE);
                viewNotify.setVisibility(View.VISIBLE);
            }
        });
    }

    private void showUserInfor() {
        if(user == null) {
            Toast.makeText(this, "Chua co tai khoan nao duoc dang ky!", Toast.LENGTH_SHORT).show();
            return;
        }

//        Intent i = new Intent(this, UserInforActivity.class);
//        i.putExtra("fullname", user.getFullname());
//        i.putExtra("email", user.getEmail());
//        i.putExtra("address", user.getAddress());
//
//        startActivity(i);
        //Dialog default
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setTitle("Thong Tin Nguoi Dung")
//                .setMessage(user.toString())
//                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//
//                    }
//                })
//                .setNegativeButton("Close", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//
//                    }
//                })
//                .show();
        //Custom
        View v = LayoutInflater.from(this).inflate(R.layout.user_infor_view, null);
        TextView txtDialogFullname = v.findViewById(R.id.uiv_fullname);
        TextView txtDialogAddress = v.findViewById(R.id.uiv_address);
        TextView txtDialogEmail = v.findViewById(R.id.uiv_email);

        Button btnClose = v.findViewById(R.id.uiv_btn_close);

        txtDialogFullname.setText(user.getFullname());
        txtDialogAddress.setText(user.getAddress());
        txtDialogEmail.setText(user.getEmail());

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(v);
        final AlertDialog dialog = builder.show();

        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }

    private void showRegisterActivity() {
        Intent i = new Intent(this, RegisterActivity.class);

//        startActivity(i);
        startActivityForResult(i, CODE_REGISTER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(resultCode == CODE_REGISTER) {
            String fullname = data.getStringExtra("fullname");
            String email = data.getStringExtra("email");
            String address = data.getStringExtra("address");
            String pwd = data.getStringExtra("password");

            user = new User(fullname, email, address, pwd);

            Toast.makeText(this, "Dang ky thanh cong", Toast.LENGTH_SHORT).show();
        }
    }

    private void checkLogin() {
        if(user == null) {
            Toast.makeText(this, "Chua co tai khoan nao duoc dang ky!", Toast.LENGTH_SHORT).show();
            return;
        }

        String email = txtEmail.getText().toString();
        String pwd = txtPwd.getText().toString();

        if(email.equalsIgnoreCase(user.getEmail()) && pwd.equals(user.getPwd())) {
            //Login success
            Toast.makeText(this, "Dang nhap thanh cong", Toast.LENGTH_SHORT).show();
        } else {
            //Login failed
            Toast.makeText(this, "Kiem tra email hoac password", Toast.LENGTH_SHORT).show();
        }
    }
}


#AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="gokisoft.j2010g">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity" />
        <activity android:name=".TestActivity" />
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".RegisterActivity" />
        <activity android:name=".UserInforActivity"></activity>
    </application>

</manifest>


#user_infor_view.xml


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

    <TextView
        android:id="@+id/uiv_fullname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorRed"
        android:text="TextView" />

    <TextView
        android:id="@+id/uiv_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorAccent"
        android:text="TextView" />

    <TextView
        android:id="@+id/uiv_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimary"
        android:text="TextView" />

    <Button
        android:id="@+id/uiv_btn_close"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Close" />
</LinearLayout>


#activity_user_infor.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:padding="5dp"
    tools:context="gokisoft.j2010g.UserInforActivity">

    <TextView
        android:id="@+id/textView5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="18pt"
        android:textColor="@color/colorRed"
        android:text="Show User Information" />

    <TextView
        android:id="@+id/aui_txt_fullname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/aui_txt_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/aui_txt_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />
</LinearLayout>


#activity_test.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="gokisoft.j2010g.TestActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="50dp"
        android:textColor="@color/colorRed"
        android:textAlignment="center"
        android:text="Welcome to learn Android" />
</LinearLayout>


#activity_register.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:padding="5dp"
    tools:context="gokisoft.j2010g.RegisterActivity">

    <TextView
        android:id="@+id/textView4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="18pt"
        android:textColor="@color/colorRed"
        android:text="Register" />

    <EditText
        android:id="@+id/ar_txt_fullname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="Enter full name"
        android:text="" />

    <EditText
        android:id="@+id/ar_txt_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter email"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/ar_txt_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter address"
        android:inputType="textPersonName"
        android:text="" />

    <EditText
        android:id="@+id/ar_txt_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter password"
        android:inputType="textPassword" />

    <EditText
        android:id="@+id/ar_txt_confirm_pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter confirm password"
        android:inputType="textPassword" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="2"
        android:orientation="horizontal">
        <Button
            android:id="@+id/ar_btn_register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Register" />

        <Button
            android:id="@+id/ar_btn_back"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Back" />
    </LinearLayout>
</LinearLayout>


#activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="gokisoft.j2010g.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:textAlignment="center"
        android:textColor="@color/colorRed"
        android:textSize="25dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textSize="16dp"
        android:text="Email:" />

    <EditText
        android:id="@+id/am_ed_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:padding="10dp"
        android:hint="Enter email"
        android:textSize="16dp"
        android:inputType="textPersonName"
        android:text="" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="16dp"
        android:padding="10dp"
        android:text="Password:" />

    <EditText
        android:id="@+id/am_ed_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:textSize="16dp"
        android:padding="10dp"
        android:hint="Enter password"
        android:inputType="textPersonName"
        android:text="" />

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

        <Button
            android:id="@+id/am_btn_save"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Save Data" />

        <Button
            android:id="@+id/am_btn_reset"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Reset Data" />
    </LinearLayout>

    <Button
        android:id="@+id/am_btn_start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Test Activity" />

</LinearLayout>


#activity_login.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:padding="5dp"
    tools:context="gokisoft.j2010g.LoginActivity">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="18pt"
        android:textColor="@color/colorRed"
        android:text="Login" />

    <EditText
        android:id="@+id/al_txt_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="Enter email"
        android:text="" />

    <EditText
        android:id="@+id/al_txt_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword"
        android:hint="Enter password"
        android:text="" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="2"
        android:orientation="horizontal">
        <Button
            android:id="@+id/al_btn_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Login" />

        <Button
            android:id="@+id/al_btn_register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="New Register" />
    </LinearLayout>

    <Button
        android:id="@+id/al_btn_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show User Infor" />

    <Button
        android:id="@+id/al_btn_load_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Load Data from Cache" />

    <TextView
        android:id="@+id/al_view_notify"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Da load du lieu." />
</LinearLayout>


Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)