java - 将用户输入编辑文本与 SQLite 数据库 Android Java 进行比较

标签 java android sqlite

您好,我正在制作一个教师助理应用程序,该应用程序使用 SQLite 数据库,允许老师通过添加更新和删除学生来考勤,每次添加新学生时都会生成学生 ID,现在这里是如何显示如果教师的输入与数据库中的学生 ID 不匹配,则会显示错误消息,而不是使我的应用程序崩溃。

学生操作

    package com.appcreator.isa.theteacherassistantapp.Database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.appcreator.isa.theteacherassistantapp.Model.Student;
import java.util.ArrayList;
import java.util.List;

public class StudentOperations
{
    public static final String LOGTAG = "STD_MNGMNT_SYS";

    SQLiteOpenHelper dbhandler;
    SQLiteDatabase database;

    private static final String[] allColumns = {
            StudentDatabaseHandler.COLUMN_SID,
            StudentDatabaseHandler.COLUMN_EID,
            StudentDatabaseHandler.COLUMN_FIRST_NAME,
            StudentDatabaseHandler.COLUMN_LAST_NAME,
            StudentDatabaseHandler.COLUMN_STUDY,
            StudentDatabaseHandler.COLUMN_ATTENDANCE

    };

    public StudentOperations(Context context)
    {
        dbhandler = new StudentDatabaseHandler(context);
    }

    public void open()
    {
        Log.i(LOGTAG,"Database Opened");
        database = dbhandler.getWritableDatabase();
    }
    public void close()
    {
        Log.i(LOGTAG, "Database Closed");
        dbhandler.close();
    }
    public Student addStudent(Student Student)
    {
        ContentValues values  = new ContentValues();
        values.put(StudentDatabaseHandler.COLUMN_EID, Student.getEnrlomentID());
        values.put(StudentDatabaseHandler.COLUMN_FIRST_NAME,Student.getFirstname());
        values.put(StudentDatabaseHandler.COLUMN_LAST_NAME,Student.getLastname());
        values.put(StudentDatabaseHandler.COLUMN_STUDY, Student.getStudy());
        values.put(StudentDatabaseHandler.COLUMN_ATTENDANCE, Student.getAttendance());
        long insertSID = database.insert(StudentDatabaseHandler.TABLE_STUDENTS,null,values);
        Student.setStudentID(insertSID);
        return Student;
    }

    // Getting single Student
    public Student getStudent(long id)
    {
        Cursor cursor = database.query(StudentDatabaseHandler.TABLE_STUDENTS,allColumns,StudentDatabaseHandler.COLUMN_SID + "=?",new String[]{String.valueOf(id)},null,null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Student e = new Student(Long.parseLong(cursor.getString(0)),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5));
        // return Student
        return e;
    }

    public List<Student> getAllStudents()
    {
        Cursor cursor = database.query(StudentDatabaseHandler.TABLE_STUDENTS,allColumns,null,null,null, null, null);

        List<Student> students = new ArrayList<>();
        if(cursor.getCount() > 0)
        {
            while(cursor.moveToNext())
            {
                Student student = new Student();
                student.setStudentID(cursor.getLong(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_SID)));
                student.setEnrlomentID(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_EID)));
                student.setFirstname(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_FIRST_NAME)));
                student.setLastname(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_LAST_NAME)));
                student.setStudy(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_STUDY)));
                student.setAttendance(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_ATTENDANCE)));
                students.add(student);
            }
        }
        // return All Students
        return students;
    }




    // Updating Student
    public int updateStudent(Student student)
    {
        ContentValues values = new ContentValues();
        values.put(StudentDatabaseHandler.COLUMN_EID, student.getEnrlomentID());
        values.put(StudentDatabaseHandler.COLUMN_FIRST_NAME, student.getFirstname());
        values.put(StudentDatabaseHandler.COLUMN_LAST_NAME, student.getLastname());
        values.put(StudentDatabaseHandler.COLUMN_STUDY, student.getStudy());
        values.put(StudentDatabaseHandler.COLUMN_ATTENDANCE, student.getAttendance());

        // updating row
        return database.update(StudentDatabaseHandler.TABLE_STUDENTS, values,
                StudentDatabaseHandler.COLUMN_SID + "=?",new String[] { String.valueOf(student.getStudentID())});
    }

    // Deleting Student
    public void removeStudent(Student student)
    {
        database.delete(StudentDatabaseHandler.TABLE_STUDENTS, StudentDatabaseHandler.COLUMN_SID + "=" + student.getStudentID(), null);
    }



}

主要 Activity

    package com.appcreator.isa.theteacherassistantapp;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.appcreator.isa.theteacherassistantapp.Database.StudentDatabaseHandler;
import com.appcreator.isa.theteacherassistantapp.Database.StudentOperations;
import com.appcreator.isa.theteacherassistantapp.Model.Student;

public class MainActivity extends AppCompatActivity
{

    private Button addStudentButton;
    private Button editStudentButton;
    private Button deleteStudentButton;

    private StudentOperations studentOps;
    private static final String EXTRA_STUDENT_ID = "TEMP";
    private static final String EXTRA_ADD_UPDATE = "TEMP";
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addStudentButton = (Button) findViewById(R.id.button_add_student);
        editStudentButton = (Button) findViewById(R.id.button_edit_student);
        deleteStudentButton = (Button) findViewById(R.id.button_delete_student);




        addStudentButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
                i.putExtra(EXTRA_ADD_UPDATE, "Add");
                startActivity(i);
            }
        });
        editStudentButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                getStudentIDAndUpdateStudent();
            }
        });
        deleteStudentButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                getStudentIDAndRemoveStudent();
            }
        });

    }


    public void getStudentIDAndUpdateStudent()
    {

        LayoutInflater li = LayoutInflater.from(this);
        View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        // set dialog_get_student_id.xml to alertdialog builder
        alertDialogBuilder.setView(getStudentIdView);

        final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);

        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id)
                    {
                        if (userInput.getText().toString().trim().length() > 0)
                        {
                                // get user input and set it to result
                                // edit text
                                Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
                                i.putExtra(EXTRA_ADD_UPDATE, "Update");
                                i.putExtra(EXTRA_STUDENT_ID, Long.parseLong(userInput.getText().toString()));
                                startActivity(i);
                        }
                        else
                        {
                            Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).create()
                .show();
    }


    public void getStudentIDAndRemoveStudent(){

        LayoutInflater li = LayoutInflater.from(this);
        View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        // set dialog_get_student_id.xml to alertdialog builder
        alertDialogBuilder.setView(getStudentIdView);

        final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);

        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id)
                    {
                        if (userInput.getText().toString().trim().length() > 0)
                        {
                                // get user input and set it to result
                                // edit text
                                //studentOps = new StudentOperations(MainActivity.this); disabled because placing it here causes error
                                studentOps.removeStudent(studentOps.getStudent(Long.parseLong(userInput.getText().toString())));
                                Toast.makeText(MainActivity.this, "Student has been removed successfully", Toast.LENGTH_SHORT).show();
                        }
                        else
                        {
                            Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).create()
                .show();
    }
@Override
    protected void onResume()
    {
        super.onResume();
        studentOps = new StudentOperations(MainActivity.this);
        studentOps.open();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        studentOps.close();
    }
}

日志猫

10-17 03:42:09.750 11105-11105/com.appcreator.isa.theteacherassistantapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.appcreator.isa.theteacherassistantapp, PID: 11105
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
    at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
    at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
    at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
    at com.appcreator.isa.theteacherassistantapp.Database.StudentOperations.getStudent(StudentOperations.java:71)
    at com.appcreator.isa.theteacherassistantapp.MainActivity$5.onClick(MainActivity.java:144)
    at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:241)
    at android.app.ActivityThread.main(ActivityThread.java:6274)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

更新了主要 Activity

    package com.appcreator.isa.theteacherassistantapp;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.appcreator.isa.theteacherassistantapp.Database.StudentDatabaseHandler;
import com.appcreator.isa.theteacherassistantapp.Database.StudentOperations;
import com.appcreator.isa.theteacherassistantapp.Model.Student;

public class MainActivity extends AppCompatActivity
{

    private Button addStudentButton;
    private Button editStudentButton;
    private Button deleteStudentButton;
    private StudentOperations studentOps;
    private static final String EXTRA_STUDENT_ID = "TEMP";
    private static final String EXTRA_ADD_UPDATE = "TEMP";

    private static final String TAG = "Student Exits";


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addStudentButton = (Button) findViewById(R.id.button_add_student);
        editStudentButton = (Button) findViewById(R.id.button_edit_student);
        deleteStudentButton = (Button) findViewById(R.id.button_delete_student);




        addStudentButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
                i.putExtra(EXTRA_ADD_UPDATE, "Add");
                startActivity(i);
            }
        });
        editStudentButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                getStudentIDAndUpdateStudent();
            }
        });
        deleteStudentButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                getStudentIDAndRemoveStudent();
            }
        });

    }

    public boolean check_existence(String stud_id)
    {
        SQLiteOpenHelper db = new StudentDatabaseHandler(this);
        SQLiteDatabase database = db.getWritableDatabase();

        String select = "SELECT * FROM students WHERE studentID =" + stud_id;

        Cursor c = database.rawQuery(select, null);

        if (c.moveToFirst())
        {
            Log.d(TAG,"Student Exists");
            return true;
        }

        if(c!=null)
        {
            c.close();
        }
        database.close();
        return false;
    }

    public void getStudentIDAndUpdateStudent()
    {

        LayoutInflater li = LayoutInflater.from(this);
        final View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        // set dialog_get_student_id.xml to alertdialog builder
        alertDialogBuilder.setView(getStudentIdView);

        final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);

        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog,int id)
                    {
                        if (userInput.getText().toString().isEmpty())
                        {
                            Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
                        }
                        else
                        {
                                // get user input and set it to result
                                // edit text
                                if (check_existence(userInput.getText().toString()) == true)
                                {
                                    Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
                                    i.putExtra(EXTRA_ADD_UPDATE, "Update");
                                    i.putExtra(EXTRA_STUDENT_ID, Long.parseLong(userInput.getText().toString()));
                                    startActivity(i);
                                }
                                else
                                {
                                    Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
                                }

                        }
                    }
                }).create()
                .show();
    }


    public void getStudentIDAndRemoveStudent()
    {

        LayoutInflater li = LayoutInflater.from(this);
        View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        // set dialog_get_student_id.xml to alertdialog builder
        alertDialogBuilder.setView(getStudentIdView);

        final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);


        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id)
                    {
                        if (userInput.getText().toString().isEmpty())
                        {
                            Toast.makeText(MainActivity.this, "Invalid Input", Toast.LENGTH_SHORT).show();
                        }
                        else
                        {
                            if(check_existence(userInput.getText().toString()) == true)
                            {
                                // get user input and set it to result
                                // edit text
                                //studentOps = new StudentOperations(MainActivity.this); disabled because placing it here causes error
                                studentOps.removeStudent(studentOps.getStudent(Long.parseLong(userInput.getText().toString())));
                                Toast.makeText(MainActivity.this, "Student has been removed successfully", Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                Toast.makeText(MainActivity.this, "Invalid Input" , Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }).create()
                .show();
    }



    @Override
    protected void onResume()
    {
        super.onResume();
        studentOps = new StudentOperations(MainActivity.this);
        studentOps.open();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        studentOps.close();
    }
}

最佳答案

您可以创建一个新方法来处理 boolean 数据类型,如果它返回 false,您可能希望通过 Toast 或其他方式将其显示给用户像这样。

代码可能如下所示:

public boolean check_existence(String stud_id) {

        SQLiteDatabase db = this.getWritableDatabase();
        String select = "SELECT * FROM table_name WHERE column_name ='" + stud_id;

        Cursor c = db.rawQuery(select, null);

        if (c.moveToFirst()) {

            Log.d(TAG,"User exits");
            return true;
        }

        if(c!=null) {

            c.close();
        }
        db.close();
        return false;
}

您现在只需调用该方法,如果它返回 false,您就可以使用 Toast 显示您想要的内容。

关于java - 将用户输入编辑文本与 SQLite 数据库 Android Java 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52827807/

相关文章:

Android:在扩展 View 中调用父类的方法

android - 关于删除级联android 2.2

python - Django 查询特殊字符

java - 如何让我的命令在我的世界上运行?

java - 如何使用系统属性实现参数?

java - 日历的 AM 和 PM 值在 12 点错了吗?

java - 无类 已注册云端点

sql - 在SQLite中,如何使用另一个表中的列值将新列插入s表中?

java - 一对多验证

java - JAVA 中 XML 的有序列表级别