Android Studio中基于SQLite数据库自动填充EditText的实现问询
实现EditText联动:输入Student ID自动填充姓名字段
我来帮你搞定这个联动填充的需求,思路其实很清晰:监听Student ID输入框的变化,输入完成后去SQLite数据库匹配对应数据,查到结果就自动填到姓名字段里。下面是具体的实现方案和代码修改建议:
1. 给Student ID输入框添加焦点监听
为了避免频繁查询数据库,建议在用户输入完Student ID并离开输入框(失去焦点)时触发查询逻辑,这样更合理:
studentid.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { // 输入框失去焦点时执行查询 if (!hasFocus) { String id = studentid.getText().toString().trim(); if (!id.isEmpty()) { getStudentInfoById(id); } else { // ID为空时清空姓名字段 fname.setText(""); lname.setText(""); } } } });
2. 实现数据库查询方法
写一个专门的方法,根据Student ID从数据库中获取对应的姓名信息:
private void getStudentInfoById(String studentId) { Cursor cursor = null; try { // 使用占位符查询,避免SQL注入 cursor = db.rawQuery("SELECT fname, lname FROM CUSTOMER_TABLE WHERE studentid = ?", new String[]{studentId}); if (cursor.moveToFirst()) { // 提取查询结果并填充到对应输入框 String firstName = cursor.getString(cursor.getColumnIndexOrThrow("fname")); String lastName = cursor.getString(cursor.getColumnIndexOrThrow("lname")); fname.setText(firstName); lname.setText(lastName); } else { // 未找到对应记录时清空字段并提示 fname.setText(""); lname.setText(""); Toast.makeText(this, "No student found with this ID", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "Error querying database", Toast.LENGTH_SHORT).show(); } finally { // 关闭Cursor,防止内存泄漏 if (cursor != null) { cursor.close(); } } }
3. 完整的MainActivity修改后代码
把上面的逻辑整合到你的代码中,同时补全你未完成的Add按钮点击事件:
public class MainActivity extends Activity { EditText fname, lname, classid, classname, pointgrade, lettergrade, studentid; Button add, viewall, delete, modifystudent, modifyclass, modifygrade; SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化所有控件 studentid = findViewById(R.id.studentID); fname = findViewById(R.id.firstName); lname = findViewById(R.id.lastName); classid = findViewById(R.id.classID); classname = findViewById(R.id.className); pointgrade = findViewById(R.id.gradePoint); lettergrade = findViewById(R.id.letterGrade); add = findViewById(R.id.addbtn); viewall = findViewById(R.id.viewall); delete = findViewById(R.id.deletebtn); modifystudent = findViewById(R.id.modifystudent); modifyclass = findViewById(R.id.modifyclass); modifygrade = findViewById(R.id.modifygrade); // 初始化数据库 db = openOrCreateDatabase("STUDENTGRADES", Context.MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS CUSTOMER_TABLE(studentid VARCHAR, fname VARCHAR, lname VARCHAR, classid VARCHAR, classname VARCHAR, pointgrade INTEGER, lettergrade VARCHAR);"); // 添加Student ID的焦点监听,触发自动填充 studentid.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { String id = studentid.getText().toString().trim(); if (!id.isEmpty()) { getStudentInfoById(id); } else { fname.setText(""); lname.setText(""); } } } }); // 补全Add按钮的点击事件 add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String id = studentid.getText().toString().trim(); String first = fname.getText().toString().trim(); String last = lname.getText().toString().trim(); String cid = classid.getText().toString().trim(); String cname = classname.getText().toString().trim(); String point = pointgrade.getText().toString().trim(); String letter = lettergrade.getText().toString().trim(); // 简单非空校验 if (id.isEmpty() || first.isEmpty() || last.isEmpty()) { Toast.makeText(MainActivity.this, "Please fill required fields", Toast.LENGTH_SHORT).show(); return; } // 用ContentValues插入数据,更安全规范 ContentValues values = new ContentValues(); values.put("studentid", id); values.put("fname", first); values.put("lname", last); values.put("classid", cid); values.put("classname", cname); values.put("pointgrade", point.isEmpty() ? 0 : Integer.parseInt(point)); values.put("lettergrade", letter); db.insert("CUSTOMER_TABLE", null, values); Toast.makeText(MainActivity.this, "Record added successfully", Toast.LENGTH_SHORT).show(); clearAllFields(); } }); // 其他按钮的点击事件可以继续补充... } // 查询学生信息的方法 private void getStudentInfoById(String studentId) { Cursor cursor = null; try { cursor = db.rawQuery("SELECT fname, lname FROM CUSTOMER_TABLE WHERE studentid = ?", new String[]{studentId}); if (cursor.moveToFirst()) { String firstName = cursor.getString(cursor.getColumnIndexOrThrow("fname")); String lastName = cursor.getString(cursor.getColumnIndexOrThrow("lname")); fname.setText(firstName); lname.setText(lastName); } else { fname.setText(""); lname.setText(""); Toast.makeText(this, "No matching student found", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "Database error occurred", Toast.LENGTH_SHORT).show(); } finally { if (cursor != null) { cursor.close(); } } } // 清空所有输入框的辅助方法 private void clearAllFields() { studentid.setText(""); fname.setText(""); lname.setText(""); classid.setText(""); classname.setText(""); pointgrade.setText(""); lettergrade.setText(""); } // 销毁Activity时关闭数据库连接 @Override protected void onDestroy() { super.onDestroy(); if (db != null && db.isOpen()) { db.close(); } } }
4. 格式化后的XML布局代码
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#d5ebfd" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="40dp" android:fontFamily="serif" android:gravity="center" android:text="Student Grade Management System" android:textColor="#ff0000" android:textSize="20sp" android:textStyle="bold"/> <EditText android:id="@+id/studentID" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Enter Student ID (Used for Updating/Deleting): " android:inputType="number" android:paddingTop="20dp" /> <requestFocus /> <EditText android:id="@+id/firstName" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Enter First Name: " /> <EditText android:id="@+id/lastName" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Enter Last Name: " /> <EditText android:id="@+id/classID" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Enter Class ID: " android:inputType="number" /> <EditText android:id="@+id/className" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Enter Class Name: " /> <EditText android:id="@+id/gradePoint" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Enter Grade Point (0-100): " android:inputType="number" /> <EditText android:id="@+id/letterGrade" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Enter Letter Grade: " /> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp"> <Button android:id="@+id/addbtn" android:layout_width="200dp" android:layout_height="50dp" android:text="Add" /> <Button android:id="@+id/deletebtn" android:layout_width="200dp" android:layout_height="50dp" android:text="Delete" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp"> <Button android:id="@+id/viewall" android:layout_width="200dp" android:layout_height="50dp" android:text="View" /> <Button android:id="@+id/modifystudent" android:layout_width="200dp" android:layout_height="50dp" android:text="Update Student Info" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp"> <Button android:id="@+id/modifyclass" android:layout_width="200dp" android:layout_height="50dp" android:text="Update Class Info" /> <Button android:id="@+id/modifygrade" android:layout_width="200dp" android:layout_height="50dp" android:text="Update Grade Info" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0.74"> </LinearLayout> </LinearLayout>
额外小建议
- 如果想要实时监听输入(比如每输入一个字符就查询),可以用
TextWatcher的afterTextChanged方法,但记得加个延迟(比如用Handler.postDelayed),避免频繁查询影响性能。 - 数据库操作建议放在子线程中执行,避免阻塞主线程导致UI卡顿,后续可以考虑用
AsyncTask或者Coroutine优化。
内容的提问来源于stack exchange,提问作者Tanner Tattini




