Android development: write a simple ledger based on Android Studio

foreword

The program I am writing recently involves user registration/login and SQLite database operations. So I sorted out the written code and wrote a simple ledger demo. The main functions include: user registration/login, user new fund records (including amount, time, user name), all fund record display, all data storage uses SQLite database. The current function is relatively rough, and everyone is welcome to discuss and improve it together.

User registration/login

For the drawing of the registration/login interface, please refer to my previous article:
Android Development: Writing the Login/Registration Interface,
which describes the drawing of the interface in detail. In this article, only the main code in Activity is posted.
In this module, two methods are written, which are used to query the information indexed by the current user name (including whether the user exists and the user's password) for judgment; and insert a row into the table storing user information in the database New record (used to implement the registration function).
The first method:

String queryUser(String Username){
    
    
        //查询结果
        String res = "";
        //数据库声明
        SQLiteDatabase mDbUser;
        Cursor Count_cursor;
        //对存储于手机本地的记录进行读取
        mDbUser = openOrCreateDatabase("upCount.db", Context.MODE_PRIVATE, null);
        mDbUser.execSQL("CREATE TABLE IF NOT EXISTS user (_id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR, password VARCHAR)");
        Count_cursor = mDbUser.rawQuery("SELECT * FROM user WHERE _id >= ?", new String[]{
    
    "1"});
        //若查询到当前用户,则退出
        while (Count_cursor.moveToNext()){
    
    
            String username = Count_cursor.getString(Count_cursor.getColumnIndex("username"));
            if (username.equals(Username)){
    
    
                res = Count_cursor.getString(Count_cursor.getColumnIndex("password"));
            }
        }
        //关闭数据库连接
        Count_cursor.close();
        mDbUser.close();
        return res;
    }

The second method:

void createUser(String Username, String Password){
    
    
        //数据库声明
        SQLiteDatabase mDbUser;
        //SQLite数据库处理
        mDbUser = openOrCreateDatabase("upCount.db",  Context.MODE_PRIVATE, null);
        mDbUser.execSQL("CREATE TABLE IF NOT EXISTS user (_id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR, password VARCHAR)");
        mDbUser.execSQL("INSERT INTO user VALUES (NULL, ?, ?)",new Object[]{
    
    Username, Password});
        //关闭数据库连接
        mDbUser.close();
    }

The code of the click event is as follows:
(1) "Register" Button:

//点击注册,触发点击事件
        mBtnRegister.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                //获取用户输入的账号及密码,传送到服务器进行判断
                Username = mEtUsername.getText().toString();
                Password = mEtPassword.getText().toString();
                //确保用户输入不为空值
                if (Username.equals("")){
    
    
                    Toast.makeText(getApplicationContext(), "用户名不能为空!", Toast.LENGTH_SHORT).show();
                }else if(Password.equals("")){
    
    
                    Toast.makeText(getApplicationContext(), "密码不能为空!", Toast.LENGTH_SHORT).show();
                }else {
    
    
                    if(!queryUser(LoginActivity.Username).equals("")){
    
    
                        Toast.makeText(getApplicationContext(), "该用户已存在!", Toast.LENGTH_SHORT).show();
                    }else{
    
    
                        createUser(LoginActivity.Username, Password);
                        Toast.makeText(getApplicationContext(), "注册成功!", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                    }
                }
            }
        });

(2) "Login" Button:

//点击登录,触发点击事件
        mBtnLogin.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                //获取用户输入的账号及密码,传送到服务器进行判断
                Username = mEtUsername.getText().toString();
                Password = mEtPassword.getText().toString();
                //确保用户输入不为空
                if (Username.equals("")){
    
    
                    Toast.makeText(getApplicationContext(), "用户名不能为空!", Toast.LENGTH_SHORT).show();
                }else if(Password.equals("")){
    
    
                    Toast.makeText(getApplicationContext(), "密码不能为空!", Toast.LENGTH_SHORT).show();
                }else {
    
    
                    //调用用户信息查询方法
                    String rightPassword = queryUser(LoginActivity.Username);
                    if(rightPassword.equals("")){
    
    
                        Toast.makeText(getApplicationContext(), "该用户不存在,请注册!", Toast.LENGTH_SHORT).show();
                    }else{
    
    
                        if (Password.equals(rightPassword)){
    
    
                            Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                        }else{
    
    
                            Toast.makeText(getApplicationContext(), "密码错误!", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        });

Note: In the click event, the Username and Password should be judged to be non-empty first, so as to prevent the user from clicking the button without entering complete information, resulting in illegal values ​​being stored in the database.

New Funds Record

Creating a new fund record includes three parts: obtaining the current system time, obtaining the value of funds input by the user, and writing data to the database. The specific code is as follows:

//记录账单
        mBtnRecord.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                //获取当前时间
                date = new Date(System.currentTimeMillis());
                time = sdf.format(date);
                Toast.makeText(getApplicationContext(), "Current Time:" + time, Toast.LENGTH_SHORT).show();
                //获取用户输入的金额
                String count = mEtCount.getText().toString();
                //SQLite数据库处理
                mDbCount = openOrCreateDatabase("upCount.db",  Context.MODE_PRIVATE, null);
                mDbCount.execSQL("CREATE TABLE IF NOT EXISTS count (_id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR, time VARCHAR, count VARCHAR)");
                mDbCount.execSQL("INSERT INTO count VALUES (NULL, ?, ?, ?)",new Object[]{
    
    LoginActivity.Username, time, count});
                mDbCount.close();
            }
        });

Query all funds records of the current user

In the demo, ListView is used as the container for recording and displaying. The writing steps mainly include declaring the control, writing the adapter (Adapter), etc. For the specific use of the ListView control, please refer to this article: Android development: the use of the ListView control . Due to space reasons, I won’t go into details here, and only show the parts involved in data reading. The code is as follows:

//对存储于手机本地的记录进行读取
        mDbCount = openOrCreateDatabase("upCount.db", Context.MODE_PRIVATE, null);
        mDbCount.execSQL("CREATE TABLE IF NOT EXISTS count (_id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR, time VARCHAR, count VARCHAR)");
        Count_cursor = mDbCount.rawQuery("SELECT * FROM count WHERE _id >= ?", new String[]{
    
    "1"});
        while (Count_cursor.moveToNext()){
    
    
            String username = Count_cursor.getString(Count_cursor.getColumnIndex("username"));
            //if语句:使界面只展示目前登录用户的爬楼梯记录
            if (username.equals(LoginActivity.Username)){
    
    
                UpList upList = new UpList();
                upList.setUsername(username);
                upList.setTime(Count_cursor.getString(Count_cursor.getColumnIndex("time")));
                upList.setCount(Count_cursor.getString(Count_cursor.getColumnIndex("count")));
                upLists.add(upList);
            }
        }

The implementation logic is to first use the pointer to traverse the corresponding table in the database, add the data with the same value of the "username" field in the table as the current username to a collection list, and then display it on the interface through the Adapter.

demo interface display

(1) Registration/login interface:
Registration/login interface
(2) Main interface:
Main interface
(3) Record display interface:
Record display interface

postscript

There are many codes above, so it is recommended that you implement functions in modules, so that when an error occurs, it is easier to determine which module has a problem. Due to space reasons, I did not post all the codes in this article at once, so I can only trouble you to integrate them yourself. I will also package and upload the source code and the entire project file later, and partners who need it can download it by themselves. If you have any questions, you can comment below, and I will try my best to reply to everyone. If you don’t have points, you can search my personal official account “Chaqian” on WeChat or scan the picture below, follow it and reply to “Ledger” in the background, and you can get the source code directly. I usually post some programming-related articles on the official account, welcome everyone to pay attention~
tea move

Guess you like

Origin blog.csdn.net/weixin_46269688/article/details/117484527