Android uses java and the simplest animation to write a login registration implementation (simple version)

Posted by Digital Wallfare on Mon, 04 Oct 2021 00:52:04 +0200

2021.10.4 simple login and registration, with its own database and simple animation interface.

          Recently, learning Android java mobile development requires a login and registration interface. I don't have much time to write a simple version.

Get to the point:

Ps: you can enter the animation without adding it. It's just for practicing. You need to Free Lottie Animation Files, Tools & Plugins - LottieFiles Download an animation in json form, and then save it under the raw resource file of near project new

  What animation you need can be downloaded directly from the official website. If you don't understand the detailed process, you can say it again. Don't bother, just skip this part

First, I'll write an entry animation for my ap. This is the main interface. You need to write the filter under the registered Activity in the list file

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.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=".intoActivity">

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="900dp"
        android:src="@drawable/mainback"
        android:scaleType="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/logo"
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:layout_constraintVertical_bias=".05"
        android:src="@drawable/chat_logo"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <ImageView
        android:id="@+id/app_name"
        android:layout_width="400dp"
        android:layout_height="100dp"
        app:layout_constraintVertical_bias=".3"
        android:src="@drawable/best_name"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <com.airbnb.lottie.LottieAnimationView
        android:id="@+id/lottie"
        android:layout_width="wrap_content"
        android:layout_height="500dp"
        app:lottie_rawRes="@raw/chat"
        app:layout_constraintVertical_bias="1.2"
        app:lottie_autoPlay="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>









</androidx.constraintlayout.widget.ConstraintLayout>

      Then, the corresponding java code is not very good. Experts should not spray pure vegetable chicken, but they also simply realize an entry animation. Then the animation is fixed for a dead time, and when the time passes, it will automatically jump to the login interface. Almost jump just after the animation is loaded. A little user experience.

public class intoActivity extends AppCompatActivity {
    private TextView timetv;
    public int T = 3; //Countdown duration
    private Handler mHandler = new Handler();



    ImageView logo,back,app_name;
    LottieAnimationView lottieAnimationView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_into);
        new Thread(new MyCountDownTimer()).start();


        logo = findViewById(R.id.logo);
        back = findViewById(R.id.img);
        app_name = findViewById(R.id.app_name);

        lottieAnimationView = findViewById(R.id.lottie);


        back.animate().translationY(-2300).setDuration(1000).setStartDelay(3000);
        app_name.animate().translationY(1600).setDuration(1000).setStartDelay(3000);
        logo.animate().translationY(1900).setDuration(1000).setStartDelay(3000);
        lottieAnimationView.animate().translationY(1600).setDuration(1000).setStartDelay(3000);

    }

    class MyCountDownTimer implements Runnable{



        @Override
        public void run() {

            while (T > 0) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                T--;
            }
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                }
            });
            if(T == 0){
                Intent intent = new Intent(intoActivity.this,MainActivity.class);
                startActivity(intent);
            }
        }
    }
}

A logical implementation of the login interface is mainly to check the data in the database to see if it matches, and there are some blank judgment operations.

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button login_bt,zc_bt;
    private EditText et_pwd,et_cont;
    private DBOpenHelper mDBOpenHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        login_bt = findViewById(R.id.login_bt);
        zc_bt = findViewById(R.id.zc_bt);
        et_cont =findViewById(R.id.et_zh);
        et_pwd = findViewById(R.id.et_mm);


        login_bt.setOnClickListener(this);
        zc_bt.setOnClickListener(this);
        mDBOpenHelper = new DBOpenHelper(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.zc_bt:
                Intent intent = new Intent(MainActivity.this,RregisterActivity.class);
                startActivity(intent);
                break;

            case R.id.login_bt:
                String name =et_cont.getText().toString().trim();
                String password = et_pwd.getText().toString().trim();
                if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(password)) {
                    ArrayList<User> data = mDBOpenHelper.getAllData();
                    boolean match = false;
                    for (int i = 0; i < data.size(); i++) {
                        User user = data.get(i);
                        if (name.equals(user.getName()) && password.equals(user.getPassword())) {
                            match = true;
                            break;
                        } else {
                            match = false;
                        }
                    }
                    if (match) {
                        Toast.makeText(this, "Login succeeded", Toast.LENGTH_SHORT).show();

                    } else {
                        Toast.makeText(this, "The user name or password is incorrect. Please re-enter it", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "Please enter your user name or password", Toast.LENGTH_SHORT).show();
                }
                break;

        }

    }
}

The corresponding java logic implementation of a registration function module is written casually. I mind standardizing the naming. Ha, ignore my naming. The main thing is to implement a blank judgment, and then add some data to the database. At the same time, it uses the implementation of a verification code.

public class RregisterActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_pwd, et_count, et_pwd_check,et_yzm;
    private Button re_btn;
    private ImageView eye,mIvRegisteractivityShowcode,eyecheck;
    private String realCode;
    private DBOpenHelper mDBOpenHelper;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rregister);
        initView();
        mDBOpenHelper = new DBOpenHelper(this);
        //Displays an image of a randomly generated verification code
        mIvRegisteractivityShowcode.setImageBitmap(Code.getInstance().createBitmap());
        realCode = Code.getInstance().getCode().toLowerCase();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register_bt:
                if(checkEdit()){
                    Registersuccese();
                }
                break;
            case R.id.iv_registeractivity_showCode:
                mIvRegisteractivityShowcode.setImageBitmap(Code.getInstance().createBitmap());
                realCode = Code.getInstance().getCode().toLowerCase();
                break;

            case R.id.re_eye:
                if (et_pwd.isSelected()) {
                    et_pwd.setSelected(false);
                    et_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                } else {
                    et_pwd.setSelected(true);
                    et_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }
        }
    }



    private void initView() {
        re_btn = findViewById(R.id.register_bt);
        et_pwd = findViewById(R.id.re_et_pwd);
        et_count = findViewById(R.id.re_et_count);
        eye = findViewById(R.id.re_eye);
        et_pwd_check = findViewById(R.id.re_et_pwd_check);
        et_yzm = findViewById(R.id.re_et_yzm);
        mIvRegisteractivityShowcode = findViewById(R.id.iv_registeractivity_showCode);
        eyecheck = findViewById(R.id.re_eye_check);


        re_btn.setOnClickListener(this);
        et_pwd.setOnClickListener(this);
        eye.setOnClickListener(this);
        eyecheck.setOnClickListener(this);

        mIvRegisteractivityShowcode.setOnClickListener(this);
    }

    private boolean checkEdit(){
        if(et_count.getText().toString().trim().equals("")){
            showDialog("User name cannot be empty");
        }else if(et_pwd.getText().toString().trim().equals("")){
            showDialog("Password cannot be empty");
        }else if(!et_pwd.getText().toString().trim().equals(et_pwd_check.getText().toString().trim())){
            showDialog("The two passwords are inconsistent");
        } else{
            return true;
        }
        return false;
    }

    private void showDialog(String s) {
        AlertDialog.Builder dlg = new AlertDialog.Builder(RregisterActivity.this);
        dlg.setTitle("System reminder");
        dlg.setMessage(s);
        dlg.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        dlg.create();
        dlg.show();
    }
    //    A dialog box will pop up to remind you whether to return to login after successful registration
    private void Registersuccese() {
        String username = et_count.getText().toString().trim();
        String password = et_pwd.getText().toString().trim();
        String phoneCode = et_yzm.getText().toString().toLowerCase();
        if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(phoneCode) ) {
            if (phoneCode.equals(realCode)) {
                //Add the user name and password to the database
                mDBOpenHelper.add(username, password);
                alert();
            } else {
                showDialog("Verification code error, registration failed");
            }
        }else {
            showDialog("The information is perfect, registration failed");
        }
    }

    private void alert() {
        AlertDialog.Builder dlg = new AlertDialog.Builder(RregisterActivity.this);
        dlg.setTitle("System reminder");
        dlg.setMessage("Registration successful, return to login");
        dlg.setPositiveButton("determine", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(RregisterActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });
        dlg.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        dlg.show();
    }

}

Code doesn't say much about a module generated by the verification code. It doesn't need to be used. It's mainly used directly before

public class Code {
    /**
     * Random number array
     * The confusing number 0 and the letter O are removed
     *                Number 1 and letter I l l
     *                Number 6 and letter b
     *                Number 9 and letter q
     *                Letters C and G
     *                Letter t (often mixed with random lines)
     */
    private static final char[] CHARS = {
            '2', '3', '4', '5',  '7', '8',
            'a',  'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm',
            'n', 'p',  'r', 's',  'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B',  'D', 'E', 'F',  'H',  'J', 'K', 'M',
            'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    };

    private static Code bmpCode;

    public static Code getInstance() {
        if(bmpCode == null)
            bmpCode = new Code();
        return bmpCode;
    }

    //default settings
    //Number of default random number of verification code
    private static final int DEFAULT_CODE_LENGTH = 4;
    //Default font size
    private static final int DEFAULT_FONT_SIZE = 25;
    //Number of default lines
    private static final int DEFAULT_LINE_NUMBER = 5;
    //padding value
    private static final int BASE_PADDING_LEFT = 10, RANGE_PADDING_LEFT = 15, BASE_PADDING_TOP = 15, RANGE_PADDING_TOP = 20;
    //Default width and height of verification code
    private static final int DEFAULT_WIDTH = 100, DEFAULT_HEIGHT = 40;

    //settings decided by the layout xml
    //canvas width and height
    private int width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT;

    //random word space and pading_top
    private int base_padding_left = BASE_PADDING_LEFT, range_padding_left = RANGE_PADDING_LEFT,
            base_padding_top = BASE_PADDING_TOP, range_padding_top = RANGE_PADDING_TOP;

    //number of chars, lines; font size
    private int codeLength = DEFAULT_CODE_LENGTH, line_number = DEFAULT_LINE_NUMBER, font_size = DEFAULT_FONT_SIZE;

    //variables
    private String code;
    private int padding_left, padding_top;
    private Random random = new Random();
    //Verification code picture
    public Bitmap createBitmap() {
        padding_left = 0;

        Bitmap bp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bp);

        code = createCode();

        c.drawColor(Color.WHITE);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setTextSize(font_size);
        //Draw verification code
        for (int i = 0; i < code.length(); i++) {
            randomTextStyle(paint);
            randomPadding();
            c.drawText(code.charAt(i) + "", padding_left, padding_top, paint);
        }
        //Draw lines
        for (int i = 0; i < line_number; i++) {
            drawLine(c, paint);
        }

//        c.save( Canvas.ALL_SAVE_FLAG );// preservation
        c.save();//preservation
        c.restore();//
        return bp;
    }

    public String getCode() {
        return code;
    }

    //Generate verification code
    private String createCode() {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < codeLength; i++) {
            buffer.append(CHARS[random.nextInt(CHARS.length)]);
        }
        return buffer.toString();
    }
    //Draw interference line
    private void drawLine(Canvas canvas, Paint paint) {
        int color = randomColor();
        int startX = random.nextInt(width);
        int startY = random.nextInt(height);
        int stopX = random.nextInt(width);
        int stopY = random.nextInt(height);
        paint.setStrokeWidth(1);
        paint.setColor(color);
        canvas.drawLine(startX, startY, stopX, stopY, paint);
    }
    //Generate random colors
    private int randomColor() {
        return randomColor(1);
    }

    private int randomColor(int rate) {
        int red = random.nextInt(256) / rate;
        int green = random.nextInt(256) / rate;
        int blue = random.nextInt(256) / rate;
        return Color.rgb(red, green, blue);
    }
    //Randomly generate text style, color, thickness and inclination
    private void randomTextStyle(Paint paint) {
        int color = randomColor();
        paint.setColor(color);
        paint.setFakeBoldText(random.nextBoolean());  //true is bold and false is non bold
        float skewX = random.nextInt(11) / 10;
        skewX = random.nextBoolean() ? skewX : -skewX;
        paint.setTextSkewX(skewX); //float type parameter, negative number indicates right skew and integer indicates left skew
        //paint.setUnderlineText(true); //true is an underscore and false is a non underscore
        //paint.setStrikeThruText(true); //true is a delete line and false is a non delete line
    }
    //Randomly generated padding value
    private void randomPadding() {
        padding_left += base_padding_left + random.nextInt(range_padding_left);
        padding_top = base_padding_top + random.nextInt(range_padding_top);
    }
}

  Finally, write your own database module and declare it in java

public class DBOpenHelper extends SQLiteOpenHelper {
    /**
     * Declare a database variable db that comes with the Android SDK
     */
    private SQLiteDatabase db;

    
    public DBOpenHelper(Context context){
        super(context,"db_test",null,1);
        db = getReadableDatabase();
    }

    
    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL("CREATE TABLE IF NOT EXISTS user(" +
                "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "name TEXT," +
                "password TEXT)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        db.execSQL("DROP TABLE IF EXISTS user");
        onCreate(db);
    }
    /**
     * Next, write a user-defined addition, deletion, modification and query method
     * These methods, written here, belong here, and may not be used in the future
     * add()
     * delete()
     * update()
     * getAllData()
     */
    public void add(String name,String password){
        db.execSQL("INSERT INTO user (name,password) VALUES(?,?)",new Object[]{name,password});
    }
    public void delete(String name,String password){
        db.execSQL("DELETE FROM user WHERE name = AND password ="+name+password);
    }
    public void updata(String password){
        db.execSQL("UPDATE user SET password = ?",new Object[]{password});
    }

    /*
     * The contents we query need to be stored in a container for use,
     * Therefore, a list of ArrayList class is defined
     * With the container, it's time to query data from the table,
     * The Cursor cursor is used here, which is the foundation of the database,
     * I won't go into details in Android, because my database skills are not very thick,
     * But I know that if Cursor is needed, the first parameter is "table name", and the middle five are null,
     * Finally, the sorting method of the queried content: "name DESC"
     * After the cursor is defined, write a while loop to make the cursor swim from the header to the footer
     * In the process of swimming, the swimming data is stored in the list container
     * @return
     */
    public ArrayList<User> getAllData(){

        ArrayList<User> list = new ArrayList<User>();
        Cursor cursor = db.query("user",null,null,null,null,null,"name DESC");
        while(cursor.moveToNext()){
            @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
            @SuppressLint("Range") String password = cursor.getString(cursor.getColumnIndex("password"));
            list.add(new User(name,password));
        }
        cursor.close();
        return list;
    }
}

  The above is a case of simple jump of Android login registration. After that, there may be some more complex login cases

The case source code will be updated to gitee later

Topics: Java Android Android Studio android-studio