You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android:如何通过输入值匹配SQLite行并显示整行数据?

Solution to Query SQLite Database by ID and Display Result

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 insertCLI method, you used TABLE_CLIENTI (typo) instead of the constant TABLE_CLIENTS. Correct it to:
    db.insertWithOnConflict(TABLE_CLIENTS, null, values, SQLiteDatabase.CONFLICT_REPLACE);
    
  • In the onCreate table creation SQL, you wrote RS1 TEXT but your constant is RS1_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_CLI with NAME_CLI
  • Replace RS1_CLI with WHERE_CLI
  • Update the CREATE TABLE statement and insertCLI method to use these new column names. Then adjust the MainActivity code to fetch NAME_CLI and WHERE_CLI instead of COD_CLI and RS1_CLI.

内容的提问来源于stack exchange,提问作者John K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:07:00