首页 文章

从微调器中获取条件,并根据条件从数据库中检索列表视图中的数据

提问于
浏览
-1

我想从数据库中检索数据,以便只有那些数据应该是listview才能在真实条件下工作 . 我在XML文件中添加了两个微调器 . 一个微调器包含存储在java文件中的默认值,用于获取血型选项,第二个包含城市名称 . 我希望如果用户选择BloodGroup作为来自微调器和城市作为Gurgaon的O ve并点击搜索按钮,则该人员的详细信息将显示在两个微调器查询之后的列表视图中 .

1 回答

  • 1

    以下是如何从两个微调器应用 SelectedItem 的工作示例,然后通过单击“搜索”按钮显示,仅列出包含两个项目的行(如果有) .

    这些示例基于您提供的方案 . 也就是说,有一个特定的城市和血型组列表可以通过Spinners选择 . 记录表包括两列以及两列 _idname 的列 . 测试数据库中填充了100个随机名称,城市和血型 .

    布局 activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Blood Bank" />
    
        <Spinner
            android:id="@+id/select_bloodgroup"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </Spinner>
        <Spinner
            android:id="@+id/select_city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </Spinner>
        <Button
            android:id="@+id/search"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Search"/>
        <ListView
            android:id="@+id/records_list"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </ListView>
    </LinearLayout>
    

    DatabaseHelper DBHelper.java

    public class DBHelper extends SQLiteOpenHelper {
    
        public static final String DBNAME = "bloodbank";
        public static final int DBVERSION = 1;
        public static final String TB_RECORDS = "records";
        public static final String COl_RECORDS_ID = BaseColumns._ID;
        public static final String COL_RECORDS_NAME = "_name";
        public static final String COL_RECORDS_BLOODGROUP = "_blood_group";
        public static final String COL_RECORDS_CITY = "_city";
    
        SQLiteDatabase mDB;
    
        public DBHelper(Context context) {
            super(context,DBNAME, null, DBVERSION);
            mDB = this.getWritableDatabase();
    
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            String crtrecords = "CREATE TABLE IF NOT EXISTS " +
                    TB_RECORDS + "(" +
                    COl_RECORDS_ID + " INTEGER PRIMARY KEY," +
                    COL_RECORDS_NAME + " TEXT," +
                    COL_RECORDS_CITY + " TEXT, " +
                    COL_RECORDS_BLOODGROUP + " TEXT" +
                    ")";
            db.execSQL(crtrecords);
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    
        }
    
        public long addRecord(String name, String city, String bloodgroup) {
            ContentValues cv = new ContentValues();
            cv.put(COL_RECORDS_NAME,name);
            cv.put(COL_RECORDS_CITY,city);
            cv.put(COL_RECORDS_BLOODGROUP,bloodgroup);
            return mDB.insert(TB_RECORDS,null,cv);
        }
    
        public Cursor getrecords(String city, String bloodgroup) {
            ArrayList<String> baseargs = new ArrayList<>();
            String whereclause = null;
            if (city != null && city.length() > 0) {
                whereclause = COL_RECORDS_CITY + "=?";
                baseargs.add(city);
            }
            if (bloodgroup != null && bloodgroup.length() > 0) {
                if (whereclause != null && whereclause.length() > 0) {
                    whereclause = whereclause + " AND ";
                } else whereclause = "";
                whereclause = whereclause + COL_RECORDS_BLOODGROUP + "=?";
                baseargs.add(bloodgroup);
            }
            String[] whereargs = null;
            if (baseargs.size() > 0) {
                whereargs = new String[baseargs.size()];
                for (int i =0; i < baseargs.size();i++) {
                    whereargs[i] = baseargs.get(i);
                }
            }
            return mDB.query(TB_RECORDS,null,whereclause,whereargs,null,null,COL_RECORDS_NAME);
        }
    }
    

    调用活动 MainActivity.java : -

    public class MainActivity extends AppCompatActivity {
    
        //Specific Blood groups
        public static final String[] BLOODGROUPS = new String[]{
                "A+","A-","B+","B-","0+","0-","AB+","AB-"
        };
    
        //Specific Cities
        public static final String[] CITIES = new String[]{
                "London","Paris","New York","Montreal","Gurgaon"
        };
    
        // Some names for auto generation of test data
        static final String[] peoples_names = new String[]{
                "Fred","Mary","Bert","Anne","James","Susan","Tom","Theresa",
                "Cherles","Corrine","David","Diana","Edward","Esmerelda",
                "George","Gorgina","Harrold","Heather"
    
        };
    
        TextView mTitle;
        Spinner mBloodGroups, mCities;
        Button mSearch;
        DBHelper mDBHlpr;
        ArrayAdapter<String> mCitiesAdapter, mBloodGroupsAdapater;
        ListView mRecordsList;
        SimpleCursorAdapter mSCA;
        String mCurrentCities = "", mCurrentBloodGroups = "";
        Cursor mCsr;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mTitle = this.findViewById(R.id.title);
            mBloodGroups = this.findViewById(R.id.select_bloodgroup);
            mCities = this.findViewById(R.id.select_city);
            mSearch = this.findViewById(R.id.search);
            mRecordsList = this.findViewById(R.id.records_list);
            mCurrentCities = "";
            mCurrentBloodGroups = "";
    
            // Add some test data
            mDBHlpr = new DBHelper(this);
            if (DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DBHelper.TB_RECORDS) < 1) {
                Random rnd = new Random();
                rnd.setSeed(System.currentTimeMillis());
                for (int i = 0; i < 100; i++) {
                    mDBHlpr.addRecord(
                            peoples_names[rnd.nextInt(peoples_names.length)],
                            CITIES[rnd.nextInt(CITIES.length)],
                            BLOODGROUPS[rnd.nextInt(BLOODGROUPS.length)]
                    );
                }
            }
    
            //Setup City Spinner
            mCitiesAdapter = new ArrayAdapter<>(this,android.R.layout.simple_dropdown_item_1line,CITIES);
            mCities.setAdapter(mCitiesAdapter);
            //Setup Bloodgroups Spinner
            mBloodGroupsAdapater = new ArrayAdapter<>(this,android.R.layout.simple_dropdown_item_1line,BLOODGROUPS);
            mBloodGroups.setAdapter(mBloodGroupsAdapater);
            // Add Search Buitton Click Listener
            mSearch.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mCurrentCities = mCities.getSelectedItem().toString();
                    mCurrentBloodGroups = mBloodGroups.getSelectedItem().toString();
                    refreshList();
                }
            });
            // Initial List (All)
            refreshList();
    
        }
    
        //Setup or refresh the ListView
        private void refreshList() {
            // Grab the data
            mCsr = mDBHlpr.getrecords(mCurrentCities,mCurrentBloodGroups);
            // If first time then setup the Cursor Adapter
            if (mSCA == null) {
                mSCA = new SimpleCursorAdapter(this,
                        android.R.layout.simple_list_item_2,
                        mCsr,
                        new String[]{DBHelper.COL_RECORDS_NAME,DBHelper.COL_RECORDS_CITY},
                        new int[]{android.R.id.text1, android.R.id.text2},
                        0
                );
                mRecordsList.setAdapter(mSCA);
            }
            // If not first time then swap the cursor
            else {
                mSCA.swapCursor(mCsr);
            }
        }
    }
    

    结果

    最初显示以下内容(因为数据是随机生成的,它可能会有所不同,尽管会列出100个项目): -

    enter image description here

    选择City Gurgaon之后: - (注意结果可能会因随机数据而有所不同): -

    enter image description here

    选择血型A-: - 后(结果可能会有所不同): -

    enter image description here

    • 注意此示例有效,目的是您从提供的代码中学习并进行您的研究,如果您有后续问题,那么您应该将它们作为Stack Overflow上的单独且不同的问题提出 .

相关问题