iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 19
0
Mobile Development

Android Studio 菜鳥筆記本系列 第 19

Android Studio 菜鳥筆記本-Day 19-sharedpreference實作

  • 分享至 

  • xImage
  •  

昨天分享了sharedpreference的用法,那麼今天就來用sharedpreference做一個可以註冊、登入的程式,check it out~

先放上註冊的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"
    tools:context=".Register">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="100dp"
                android:layout_gravity="center"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="註冊畫面"
                    android:textColor="@color/black"
                    android:textSize="25sp" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="50dp"
                android:layout_marginLeft="50dp"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/account"
                    android:layout_width="100dp"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:background="@color/gray"
                    android:text="帳號"
                    android:textColor="@color/white"
                    android:textSize="20sp" />
                <EditText
                    android:id="@+id/userid"
                    android:layout_width="200dp"
                    android:layout_height="match_parent"
                    android:background="@drawable/shapeeditview"
                    android:textSize="20sp" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="300dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="50dp"
                android:orientation="horizontal">
                <TextView
                    android:id="@+id/passwd"
                    android:layout_width="100dp"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:background="@color/gray"
                    android:text="密碼"
                    android:textColor="@color/white"
                    android:textSize="20sp" />
                <EditText
                    android:id="@+id/userpasswd"
                    android:layout_width="200dp"
                    android:layout_height="match_parent"
                    android:hint="不能超過15個字"
                    android:background="@drawable/shapeeditview"
                    android:textSize="20sp"
                    android:inputType="textPassword"
                    android:maxLength="15"
                    android:ems="15"/>
            </LinearLayout>
            <LinearLayout
                android:layout_marginTop="200dp"
                android:layout_width="300dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center">
                <Button
                    android:id="@+id/cler"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@drawable/shapebutton"
                    android:text="清除"
                    android:textSize="20sp"/>
                <Button
                    android:id="@+id/comfirm"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="120dp"
                    android:background="@drawable/shapebutton"
                    android:text="確定"
                    android:textSize="20sp"/>
            </LinearLayout>
        </LinearLayout>
</LinearLayout>

註冊的程式碼

宣告物件

 private Button cler,comfirm;
 private EditText userid,userpasswd;

在onCreate()的方法中取得控制元件

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        init();//取得元件的id
        buttonlistener();//設定監聽事件

取得元件的id

private void init() {
        userid=(EditText)findViewById(R.id.userid);
        userpasswd=(EditText)findViewById(R.id.userpasswd);
        comfirm=(Button)findViewById(R.id.comfirm);
        cler=(Button)findViewById(R.id.cler);
    }

設定監聽事件

private void buttonlistener() {
  comfirm.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
         //新增一個sharedpreference
         SharedPreferences sharedPreferences =getSharedPreferences("data",MODE_PRIVATE);
         //將sharedPreferences設定為編輯模式
         SharedPreferences.Editor editor=sharedPreferences.edit();
         //存入輸入的資料
         editor.putString("id",userid.getText().toString());
         editor.putString("password",userpasswd.getText().toString());
         editor.apply();
         String str =userid.getText().toString();
         String str1 =userpasswd.getText().toString();
         //判斷輸入的值是否為空值
         if (TextUtils.isEmpty(str)) {
           Toast.makeText(Register.this, "帳號不能為空",Toast.LENGTH_SHORT).show();
             }else if (TextUtils.isEmpty(str1)) {
             Toast.makeText(Register.this, "密碼不能為空", Toast.LENGTH_SHORT).show();
           }else{
              Toast.makeText(Register.this,"註冊成功!",Toast.LENGTH_SHORT).show();
              Intent intent1=new Intent(Register.this,MainActivity.class);
              startActivity(intent1);
                     }
                }
        });
        //按下清除按鈕則清除帳號密碼
        cler.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                userid.setText("");
                userpasswd.setText("");
            }
        });
    }

避免註冊時沒輸入帳號密碼,而通過的狀況
我使用TextUtils.isEmpty()来進行判斷帳號密碼輸入是否為空值。

完整程式碼

package com.example.test1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Register extends AppCompatActivity {
    //宣告物件
    private Button cler,comfirm;
    private EditText userid,userpasswd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        init();//取得元件的id
        buttonlistener();//設定監聽事件
    }
    //取得元件的id
    private void init() {
        userid=(EditText)findViewById(R.id.userid);
        userpasswd=(EditText)findViewById(R.id.userpasswd);
        comfirm=(Button)findViewById(R.id.comfirm);
        cler=(Button)findViewById(R.id.cler);
    }
    //設定監聽事件
    private void buttonlistener() {
        comfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               //新增一個sharedpreference
               SharedPreferences sharedPreferences =getSharedPreferences("data",MODE_PRIVATE);
               SharedPreferences.Editor editor=sharedPreferences.edit();
               //存入資料
               editor.putString("id",userid.getText().toString());
               editor.putString("password",userpasswd.getText().toString());
               editor.apply();
               
               String str =userid.getText().toString();
               String str1 =userpasswd.getText().toString();
                    //判斷輸入的值是否為空值
               if (TextUtils.isEmpty(str)) {
                  Toast.makeText(Register.this, "帳號不能為空",Toast.LENGTH_SHORT).show();
               }else if (TextUtils.isEmpty(str1)) {
                  Toast.makeText(Register.this, "密碼不能為空", Toast.LENGTH_SHORT).show();
               }else{
                  Toast.makeText(Register.this,"註冊成功!",Toast.LENGTH_SHORT).show();
                  Intent intent1=new Intent(Register.this,MainActivity.class);
                  startActivity(intent1);
                    }
               }
        });
        //按下清除按鈕則清除帳號密碼
        cler.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                userid.setText("");
                userpasswd.setText("");
            }
        });
    }
}

登入的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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="100dp"
            android:layout_gravity="center"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="登入畫面"
                android:textColor="@color/black"
                android:textSize="25sp" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:layout_marginLeft="50dp"
            android:orientation="horizontal">
            <TextView
                android:id="@+id/te1"
                android:layout_width="100dp"
                android:layout_height="match_parent"
                android:gravity="center"
                android:background="@drawable/shapetextview"
                android:text="帳號"
                android:textColor="@color/white"
                android:textSize="20sp" />
            <EditText
                android:id="@+id/useraccount"
                android:layout_width="200dp"
                android:layout_height="match_parent"
                android:background="@drawable/shapeeditview"
                android:textSize="20sp" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="50dp"
            android:orientation="horizontal">
            <TextView
                android:id="@+id/te2"
                android:layout_width="100dp"
                android:layout_height="match_parent"
                android:gravity="center"
                android:background="@drawable/shapetextview"
                android:text="密碼"
                android:textColor="@color/white"
                android:textSize="20sp" />
            <EditText
                android:id="@+id/userpassword"
                android:layout_width="200dp"
                android:layout_height="match_parent"
                android:hint="不能超過15個字"
                android:background="@drawable/shapeeditview"
                android:textSize="20sp"
                android:inputType="textPassword"
                android:maxLength="15"
                android:ems="15"/>
        </LinearLayout>
        <Button
            android:id="@+id/userregister"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_marginTop="150dp"
            android:text="註冊"
            android:textSize="20sp" />
        <Button
            android:id="@+id/signin"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_marginTop="20dp"
            android:text="登入"
            android:textSize="20sp" />
    </LinearLayout>
</LinearLayout>

登入的程式設計

架構跟註冊畫面是差不多的,所以我就省略,直接放上完整的程式碼

package com.example.test1;
import androidx.annotation.ColorInt;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    private EditText useraccount,userpassword;
    private Button userregister,signin;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //取得元件的id
        components();
        //設定button的監聽事件
        buttonsetting();
        }
    //取得元件的id
    private void components() {
        useraccount=(EditText)findViewById(R.id.useraccount);
        userpassword=(EditText)findViewById(R.id.userpassword);
        userregister=(Button)findViewById(R.id.userregister);
        signin=(Button)findViewById(R.id.signin);
    }
    //設定button的監聽事件
    private void buttonsetting() {
        userregister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent main =new Intent(MainActivity.this,Register.class);
                startActivity(main);
            }
        });
        signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String userid=useraccount.getText().toString();
                String userpasswd=userpassword.getText().toString();
                //取得sharedpreference
                SharedPreferences preference=getSharedPreferences("data",MODE_PRIVATE);
                //判斷登入畫面輸入的帳號密碼是否跟註冊的帳號密碼一樣
                if (userid.equals(preference.getString("id",""))
                &&userpasswd.equals(preference.getString("password",""))){
                    SharedPreferences.Editor edit =preference.edit();
                    edit.apply();
                    //是的話顯示成功登入
                    Toast.makeText(MainActivity.this,"成功登入",Toast.LENGTH_SHORT).show();
                } else {
                    //不是則顯示登入失敗
                    Toast.makeText(MainActivity.this,"登入失敗",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

成果圖
進入登入畫面
https://ithelp.ithome.com.tw/upload/images/20200918/201294081shBt1cjIn.jpg
點擊「註冊」按鈕,進入註冊畫面
https://ithelp.ithome.com.tw/upload/images/20200918/20129408DFeyCWRCH3.jpg
防止帳號密碼未輸入
https://ithelp.ithome.com.tw/upload/images/20200918/20129408aRMtmqgpAn.jpg
https://ithelp.ithome.com.tw/upload/images/20200918/20129408muRdZ8u7YS.jpg
註冊帳號:123 註冊密碼:123,點擊「註冊」按鈕
https://ithelp.ithome.com.tw/upload/images/20200918/20129408UCrdodc4NL.jpg
進入登入畫面,如未輸入帳號密碼則登入失敗
https://ithelp.ithome.com.tw/upload/images/20200918/20129408RwF3D35cOI.jpg
輸入對的帳號密碼,則顯示成功登入
https://ithelp.ithome.com.tw/upload/images/20200918/20129408lXSaWIdZLV.jpg


上一篇
Android Studio 菜鳥筆記本-Day 18-介紹SharedPreference
下一篇
Android Studio 菜鳥筆記本-Day 20-AlertDialog的使用方法
系列文
Android Studio 菜鳥筆記本30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言