2024.4.28

一点都不难發表於2024-06-28

因為我們的程式目標計劃改變,現在目標是製作一個出遊打卡系統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>

相關文章