Android:如何通过输入值匹配SQLite行并显示整行数据?
Hey there! Let's get this working step by step. The core problem right now is your DataBaseHandler lacks a method to fetch a specific client by their ID_CLI—you only have a method to retrieve all rows. Plus, I spotted a couple of small inconsistencies in your database code that we'll fix along the way.
1. Add a Method to Query Client by ID in DataBaseHandler
First, let's add a safe, parameterized query method to get a single client row using their ID. This avoids SQL injection risks and is cleaner than raw queries:
public Cursor getClientById(String clientId) { SQLiteDatabase db = this.getReadableDatabase(); // Query the table for rows matching the given ID_CLI return db.query( TABLE_CLIENTS, null, // Fetch all columns ID_CLI + " = ?", // WHERE clause: match ID_CLI to input new String[]{clientId}, // Replace ? with the actual ID (prevents SQL injection) null, null, null ); }
2. Fix Existing Bugs in DataBaseHandler
I noticed two small errors in your current code:
- In the
insertCLImethod, you usedTABLE_CLIENTI(typo) instead of the constantTABLE_CLIENTS. Correct it to:db.insertWithOnConflict(TABLE_CLIENTS, null, values, SQLiteDatabase.CONFLICT_REPLACE); - In the
onCreatetable creation SQL, you wroteRS1 TEXTbut your constant isRS1_CLI. Update the CREATE statement to match your column name:String CREATE_TABLE_CLIENTS = "CREATE TABLE IF NOT EXISTS " + TABLE_CLIENTS + " (ID_CLI TEXT,COD_CLI TEXT,RS1_CLI TEXT)";
3. Implement the Click Logic in MainActivity
Now, wire up your EditText, Button, and TextView to handle the search action. Here's a complete example of the activity code:
import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import android.database.Cursor; public class MainActivity extends AppCompatActivity { private EditText etClientId; private Button btnSearch; private TextView tvResult; private DataBaseHandler dbHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize UI elements (make sure these IDs match your layout file) etClientId = findViewById(R.id.et_client_id); btnSearch = findViewById(R.id.btn_search); tvResult = findViewById(R.id.tv_result); // Get instance of your database handler dbHandler = DataBaseHandler.getInstance(this); // Set click listener for the search button btnSearch.setOnClickListener(v -> { String inputId = etClientId.getText().toString().trim(); // Check if input is empty if (inputId.isEmpty()) { tvResult.setText("Please enter a client ID!"); return; } // Query the database for the client Cursor cursor = dbHandler.getClientById(inputId); if (cursor != null && cursor.moveToFirst()) { // Extract values from the cursor using column names String id = cursor.getString(cursor.getColumnIndex(DataBaseHandler.ID_CLI)); String cod = cursor.getString(cursor.getColumnIndex(DataBaseHandler.COD_CLI)); String rs1 = cursor.getString(cursor.getColumnIndex(DataBaseHandler.RS1_CLI)); // Format the result into a single line String resultLine = id + " " + cod + " " + rs1; tvResult.setText(resultLine); // Always close the cursor to avoid memory leaks cursor.close(); } else { tvResult.setText("No client found with ID: " + inputId); } }); } }
4. Match Your Table to Your Data Example (Optional)
If your actual database should use NAME_CLI and WHERE_CLI (like your data sample shows), update your DataBaseHandler constants and table creation code:
- Replace
COD_CLIwithNAME_CLI - Replace
RS1_CLIwithWHERE_CLI - Update the CREATE TABLE statement and
insertCLImethod to use these new column names. Then adjust theMainActivitycode to fetchNAME_CLIandWHERE_CLIinstead ofCOD_CLIandRS1_CLI.
内容的提问来源于stack exchange,提问作者John K

