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

Android Studio中如何将RadioButton作为SQLite筛选器?

实现RadioButton独立SQLite筛选器方案

现有代码通过多字段OR逻辑进行SQLite数据筛选,要将6个RadioButton分别对应名称、价格、类型、功率、重量、国家6个独立筛选条件,实现选中单个RadioButton时仅按对应字段筛选,具体修改步骤如下:


步骤1:修改MySQLite类的查询方法

原getData方法为固定多字段查询,需修改为支持指定单个筛选字段的版本:

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class MySQLite extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 4;
    static final String DATABASE_NAME = "phones";
    static final String TABLE_NAME = "emergency_service";
    static final String ID = "id";
    static final String NAME = "name";
    static final String PRICE = "price";
    static final String TYPE = "type";
    static final String POWER = "power";
    static final String WEIGHT = "weight";
    static final String COUNTRY = "country";

    static final String ASSETS_FILE_NAME = "vacuumcleaner.txt";
    static final String DATA_SEPARATOR = "|";
    private Context context;

    public MySQLite(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
                + ID + " INTEGER PRIMARY KEY,"
                + NAME + " TEXT,"
                + PRICE + " TEXT,"
                + TYPE + " TEXT,"
                + POWER + " TEXT,"
                + WEIGHT + " TEXT,"
                + COUNTRY + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
        loadDataFromAsset(context, ASSETS_FILE_NAME, db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public void addData(SQLiteDatabase db, String name, String price, String type, String power, String weight, String country) {
        ContentValues values = new ContentValues();
        values.put(NAME, name);
        values.put(PRICE, price);
        values.put(TYPE, type);
        values.put(POWER, power);
        values.put(WEIGHT, weight);
        values.put(COUNTRY, country);
        db.insert(TABLE_NAME, null, values);
    }

    public void loadDataFromAsset(Context context, String fileName, SQLiteDatabase db) {
        BufferedReader in = null;
        try {
            InputStream is = context.getAssets().open(fileName);
            in = new BufferedReader(new InputStreamReader(is));
            String str;
            while ((str = in.readLine()) != null) {
                String strTrim = str.trim();
                if (!strTrim.equals("")) {
                    StringTokenizer st = new StringTokenizer(strTrim, DATA_SEPARATOR);
                    String name = st.nextToken().trim();
                    String price = st.nextToken().trim();
                    String type = st.nextToken().trim();
                    String power = st.nextToken().trim();
                    String weight = st.nextToken().trim();
                    String country = st.nextToken().trim();
                    addData(db, name, price, type, power, weight, country);
                }
            }
        } catch (IOException ignored) {
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

    // 修改后的getData方法,支持指定筛选字段
    public String getData(String filter, String targetColumn) {
        String selectQuery;

        if (filter.isEmpty()) {
            selectQuery = "SELECT * FROM " + TABLE_NAME + " ORDER BY " + NAME;
        } else {
            // 指定字段则单字段筛选,否则保留原多字段逻辑
            if (targetColumn != null && !targetColumn.isEmpty()) {
                selectQuery = "SELECT * FROM " + TABLE_NAME + 
                              " WHERE " + targetColumn + " LIKE '%" + filter + "%'" +
                              " ORDER BY " + NAME;
            } else {
                selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE (" + PRICE + " LIKE '%"  +
                        filter + "%'" +
                        " OR " + TYPE + " LIKE '%" + filter + "%'" + " OR " +  POWER + " LIKE '%" + filter + "%'"
                        + " OR " + WEIGHT + " LIKE '%" + filter + "%'" + " OR " + COUNTRY +
                        " LIKE '%" + filter + "%'" + " OR " + NAME + " LIKE '%" + filter + "%'" +") ORDER BY " + NAME;
            }
        }

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        StringBuilder data = new StringBuilder();
        int num = 0;

        if (cursor.moveToFirst()) {
            do {
                String name = cursor.getString(cursor.getColumnIndex(NAME));
                String price = cursor.getString(cursor.getColumnIndex(PRICE));
                String type = cursor.getString(cursor.getColumnIndex(TYPE));
                String power = cursor.getString(cursor.getColumnIndex(POWER));
                String weight = cursor.getString(cursor.getColumnIndex(WEIGHT));
                String country = cursor.getString(cursor.getColumnIndex(COUNTRY));
                data.append(String.valueOf(++num) + ") " + name + ": " + price + ": "+ type + ": " + power + ": " + weight + ": " + country + "\n");
            } while (cursor.moveToNext());
        }
        // 关闭Cursor和数据库,避免内存泄漏
        cursor.close();
        db.close();
        return data.toString();
    }
}

步骤2:配置MainActivity的RadioButton逻辑

在MainActivity中初始化RadioGroup及RadioButton,添加选择监听并统一处理筛选逻辑:

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private final int LARGE_FONT = 16;
    private final int SMALL_FONT = 12;
    private int fontSize = SMALL_FONT;
    private MySQLite db = new MySQLite(this);
    private EditText editText;
    private TextView textView;
    private RadioGroup radioGroup;
    private RadioButton priceRadioButton;
    private RadioButton powerRadioButton;
    private RadioButton typeRadioButton;
    private RadioButton weightRadioButton;
    private RadioButton countryRadioButton;
    private RadioButton nameRadioButton;
    static final String FILTER = "FILTER";
    private String filter = "";
    // 保存当前选中的筛选字段
    private String selectedColumn = "";

    SharedPreferences sPref;
    static final String CONFIG_FILE_NAME = "Config";
    static final String FONT_SIZE = "FontSize";

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putString(FILTER, filter);
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
        textView.setKeyListener(null);

        sPref = getSharedPreferences(CONFIG_FILE_NAME, MODE_PRIVATE);
        fontSize = sPref.getInt(FONT_SIZE, SMALL_FONT);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
        textView.requestFocus();

        if (savedInstanceState != null) {
            editText.setText(savedInstanceState.getString(FILTER));
        }

        // 初始化RadioGroup和RadioButton
        radioGroup = findViewById(R.id.radioGroup);
        priceRadioButton = findViewById(R.id.radio_price);
        powerRadioButton = findViewById(R.id.radio_power);
        typeRadioButton = findViewById(R.id.radio_type);
        weightRadioButton = findViewById(R.id.radio_weight);
        countryRadioButton = findViewById(R.id.radio_country);
        nameRadioButton = findViewById(R.id.radio_name);

        // RadioGroup选择监听
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.radio_name:
                    selectedColumn = MySQLite.NAME;
                    break;
                case R.id.radio_price:
                    selectedColumn = MySQLite.PRICE;
                    break;
                case R.id.radio_type:
                    selectedColumn = MySQLite.TYPE;
                    break;
                case R.id.radio_power:
                    selectedColumn = MySQLite.POWER;
                    break;
                case R.id.radio_weight:
                    selectedColumn = MySQLite.WEIGHT;
                    break;
                case R.id.radio_country:
                    selectedColumn = MySQLite.COUNTRY;
                    break;
                default:
                    selectedColumn = "";
                    break;
            }
            performFilter();
        });

        // EditText文本变化监听
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                performFilter();
            }
        });

        // 初始加载数据
        performFilter();
    }

    // 统一执行筛选的方法
    private void performFilter() {
        new Thread(() -> {
            filter = editText.getText().toString().trim();
            final String data = db.getData(filter, selectedColumn);
            textView.post(() -> textView.setText(data));
        }).start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        menu.findItem(R.id.large_font).setChecked(fontSize == LARGE_FONT);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.email) {
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("message/rfc822");
            i.putExtra(Intent.EXTRA_EMAIL, new String[]{getString(R.string.myemail)});
            i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.Добавьте_еще_номер));
            i.putExtra(Intent.EXTRA_TEXT, getString(R.string.Предлагаю_такой_номер));
            try {
                startActivity(Intent.createChooser(i, getString(R.string.Посылка_письма)));
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(MainActivity.this, R.string.Нет_установленного_почтового_клиента, Toast.LENGTH_SHORT).show();
            }
            return true;
        }
        if (id == R.id.large_font) {
            item.setChecked(!item.isChecked());
            int size = item.isChecked() ? LARGE_FONT : SMALL_FONT;
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
            fontSize = size;
            return true;
        }
        if (id == R.id.exit) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        super.onStop();
        SharedPreferences.Editor ed = sPref.edit();
        ed.putInt(FONT_SIZE, fontSize);
        ed.apply();
    }
}

步骤3:布局文件补充(activity_main.xml)

确保布局中包含RadioGroup及对应RadioButton,示例结构如下:

<RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="8dp">

    <RadioButton
        android:id="@+id/radio_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="名称"/>

    <RadioButton
        android:id="@+id/radio_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="价格"/>

    <RadioButton
        android:id="@+id/radio_type"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="类型"/>

    <RadioButton
        android:id="@+id/radio_power"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="功率"/>

    <RadioButton
        android:id="@+id/radio_weight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="重量"/>

    <RadioButton
        android:id="@+id/radio_country"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="国家"/>
</RadioGroup>

功能说明

  • 选中任意RadioButton时,筛选逻辑仅针对对应字段执行模糊匹配
  • 未选中任何RadioButton时,自动退回到原多字段OR筛选逻辑
  • 新增performFilter方法统一处理筛选逻辑,避免代码冗余
  • 添加Cursor和数据库关闭操作,避免内存泄漏

内容的提问来源于stack exchange,提问作者Dookii Piking

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 03:45:33