因为我们的程序目标计划改变,现在目标是制作一个出游打卡系统app,所以着手开始新程序,首先是数据库连接和登录
CommonUtils.java
package com.example.share.utils;

import android.content.Context;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**

  • 自定义通用工具类
    */
    public class CommonUtils {

    /**

    • 获取当前时间的字符串
    • @return "yyyy-MM-dd HH:mm:ss" 格式的时间字符串
      */
      public static String getDateStrFromNow(){
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      return df.format(new Date());
      }

    /**

    • 从日期时间中获取时间字符串
    • @param dt 日期时间
    • @return "yyyy-MM-dd HH:mm:ss" 格式的时间字符串
      */
      public static String getStrFromDate(Date dt){
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      return df.format(dt);
      }

    /**

    • 显示短消息
    • @param context 上下文
    • @param msg 要显示的消息
      */
      public static void showShortMsg(Context context, String msg){
      Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
      }

    /**

    • 显示长消息
    • @param context 上下文
    • @param msg 要显示的消息
      */
      public static void showLonMsg(Context context, String msg){
      Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
      }

    /**

    • 显示消息对话框
    • @param context 上下文
    • @param msg 要显示的消息
      */
      public static void showDlgMsg(Context context, String msg){
      new AlertDialog.Builder(context)
      .setTitle("提示信息")
      .setMessage(msg)
      .setPositiveButton("确定", null)
      .setNegativeButton("取消", null)
      .create().show();
      }
      }
      DbOpenHelper.java
      package com.example.share.utils;

import android.util.Log;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class DbOpenHelper {
private static final String CLS="com.mysql.jdbc.Driver";
private static final String URL="jdbc:mysql://192.168.43.157:3306/tuandui?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8";
private static final String USER="root";
private static final String PASSWORD="ADGJL12345syl";

public static Connection connection; //连接对象
public static Statement statement;  //命令集
public static PreparedStatement preparedStatement;  //预编译命令集v
public static ResultSet resultSet;  //结果集
//获取连接的方法
public static void getConnection(){
    try{
        Class.forName(CLS);
        connection = DriverManager.getConnection(URL,USER,PASSWORD);

    }catch (Exception e){
        Log.e("DB_CONNECTION", "Connection Error: " + e.getMessage());
        e.printStackTrace();
    }
}

public static void closeAll(){
    try{
        if(connection != null){
            connection.close();
            connection = null;
        }
        if(statement != null){
            statement.close();
            statement = null;
        }
        if(preparedStatement != null){
            preparedStatement.close();
            preparedStatement = null;
        }
        if(resultSet != null){
            resultSet.close();
            resultSet = null;
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}

}
User.java
package com.example.share.entity;

public class User {
private String name;
private String id;
private String password;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public User() {
}

public User(String name, String id, String password) {
    this.name = name;
    this.id = id;
    this.password = password;
}

}
UserDao.java
package com.example.share.dao;

import static com.example.share.utils.DbOpenHelper.closeAll;
import static com.example.share.utils.DbOpenHelper.connection;
import static com.example.share.utils.DbOpenHelper.getConnection;

import com.example.share.entity.MyUser;
import com.example.share.utils.DbOpenHelper;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDao extends DbOpenHelper {

public int addMyUser(MyUser myUser){

    int iRow=0;
    try{
        getConnection();
        String sql = "insert into myuser values(?,?)";
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,myUser.getName());
        preparedStatement.setString(2,myUser.getPasword());
        iRow=preparedStatement.executeUpdate();


    }catch(Exception e){
        e.printStackTrace();
    }finally {
        closeAll();
    }
    return iRow;
}

public String login(String name) {
    String password = "";
    try {
        getConnection();
        String sql = "select password from myuser where name=?";
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, name);
        resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            password = resultSet.getString("password");
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        closeAll();
    }
    return password;
}

}
Mainactivity.java
package com.example.share;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

//import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.share.register;
import com.example.share.dao.UserDao;
import com.example.share.utils.CommonUtils;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button LoginButton,SignUpButton;
private EditText UserNameEdit,PassWordEdit;
UserDao userDao;
private Handler mainHandler;


@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LoginButton = findViewById(R.id.LoginButton);
    SignUpButton=findViewById(R.id.SignUpButton);

    UserNameEdit = findViewById(R.id.UserNameEdit);
    PassWordEdit = findViewById(R.id.PassWordEdit);

    userDao=new UserDao();
    mainHandler=new Handler(getMainLooper());

    LoginButton.setOnClickListener(this);
    SignUpButton.setOnClickListener(this);
}


@Override
public void onClick(View v) {
    if (v.getId() == R.id.LoginButton) {
        String name=UserNameEdit.getText().toString().trim();
        String password=PassWordEdit.getText().toString().trim();

        new Thread(new Runnable() {
            @Override
            public void run() {

                String Password="";
                String TeacherPassword="";
                Password=userDao.login(name);

                if(password.equals(Password)){
                    Intent intent=new Intent(getApplicationContext(), DongtaiActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putString("name",name);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            CommonUtils.showShortMsg(MainActivity.this,"登陆成功");
                            SharedPreferences sharedPref = getSharedPreferences("app_prefs", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPref.edit();
                            editor.putString("username", name);
                            editor.apply();
                            Intent intent=new Intent(getApplicationContext(), DongtaiActivity.class);
                        }
                    });

                }
                else if(password.equals(TeacherPassword)){
                    Intent intent=new Intent(getApplicationContext(), DongtaiActivity.class);
                    startActivity(intent);
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            CommonUtils.showShortMsg(MainActivity.this,"登陆成功");
                            Intent intent=new Intent(getApplicationContext(), DongtaiActivity.class);
                        }
                    });

                }
                else{
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            CommonUtils.showShortMsg(MainActivity.this,"登陆失败");
                        }
                    });
                }
            }
        }).start();
    }
    else if(v.getId()==R.id.SignUpButton){
        Intent intent=new Intent(getApplicationContext(), register.class);
        startActivity(intent);
    }
}




@Override
public void onPointerCaptureChanged(boolean hasCapture) {
    super.onPointerCaptureChanged(hasCapture);
}

}
activity_main.xml

<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">

<!--使用线性布局-->
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#F5F5F5">

    <!--Logo-->
    <ImageView
        android:id="@+id/LogoImage"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:layout_marginTop="100dp"
        />

    <!--标题-->
    <TextView
        android:id="@+id/TitleText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="25dp"
        android:text="登录"
        android:gravity="center"
        android:textStyle="italic"
        android:textColor="#808080"
        android:textSize="30dp" />

    <!--嵌套线性布局-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <!--嵌套线性布局-->
        <LinearLayout
            android:id="@+id/UserNameLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <!--用户名输入-->
            <EditText
                android:id="@+id/UserNameEdit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="15dp"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="15dp"
                android:background="@drawable/translucent_edit"
                android:hint="输入用户名"
                android:textSize="24dp"
                android:singleLine="true" />

        </LinearLayout>

        <!--嵌套线性布局-->
        <LinearLayout
            android:id="@+id/PassWordLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <!--密码输入-->
            <EditText
                android:id="@+id/PassWordEdit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="15dp"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="15dp"
                android:background="@drawable/translucent_edit"
                android:hint="输入用户密码"
                android:textSize="24dp"
                android:maxLength="16"
                android:singleLine="true"
                android:inputType="textPassword" />

        </LinearLayout>

        <!--嵌套线性布局-->
        <LinearLayout
            android:id="@+id/LayoutButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <!--登录按钮-->
            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/LoginButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="15dp"
                android:layout_margin="15dp"
                android:layout_weight="1"
                android:textColor="@color/white"
                android:background="@drawable/translucent_button"
                android:text="登   录"
                android:textSize="24dp" />

            <!--注册按钮-->
            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/SignUpButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="15dp"
                android:layout_margin="15dp"
                android:layout_weight="1"
                android:textColor="@color/white"
                android:background="@drawable/translucent_button"
                android:text="注   册"
                android:textSize="24dp" />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

posted on 2024-06-28 22:02  一点都不难  阅读(24)  评论(0)    收藏  举报