如何根据第一个微调器中的选择从数据库中过滤第二个微调器值?

时间:2019-02-11 19:36:37

标签: java arraylist android-sqlite android-spinner

我正在设置一个名为Dispatch Report的新活动,该活动具有两个Spinners:CustomerSpinner和LotSpinner。

LotSpinner在发货表中显示所有批次,而不是仅显示与在第一个Spinner中选择的客户相关的那些批次。

我已经从调度表中获取了CustomerSpinner值。在LotSpinner中,还从调度表中提取了批号,但未根据客户选择进行过滤。

DispatchReportActivity.Java

// Fetching customer from dispatch table  
private void loadCustomerNameDispatch() {
    DatabaseHelper db = new DatabaseHelper( getApplicationContext() );

        List<String> lables1 = db.getFirmNAmeMoveStock();
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, lables1);
        dataAdapter           .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // attaching data adapter to spinner
        spinCustomer.setAdapter(dataAdapter);
        spinCustomer.setOnItemSelectedListener(this);
    }

// Fetching lot from dispatch table
    private void loadLotbyCustomerDispatch() {
        // database handler
        DatabaseHelper db = new DatabaseHelper(getApplicationContext());
        // Spinner Drop down elements
        List<String> lables = db.getLotbyCustomer();
        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, lables);
        // Drop down layout style - list view with radio button
        dataAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // attaching data adapter to spinner
        spinLotbyCustomer.setAdapter(dataAdapter);
    }

DATABASEHELPER.Java

//Get firm name in Dispatch Stock Report screen
public List < String > getFirmNAmeMoveStock() {
    List < String > labels = new ArrayList < String > ();

    // Select all query
    String selectQuery = "SELECT * FROM " + Table_Inventory;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // Looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            labels.add(cursor.getString(3));
            Set < String > set = new HashSet < >(labels);
            labels.clear();
            labels.addAll(set);
        } while ( cursor . moveToNext ());
    }

    // Closing connection
    cursor.close();
    db.close();

    // Returning lables
    return labels;
}

// Method to get Lot No. in Dispatch Stock Report Activity
public List < String > getLotbyCustomer() {
    List < String > labels1 = new ArrayList < String > ();

    // Select all query
    String selectQuery = "SELECT * FROM " + Table_StockDispatch;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            labels1.add(cursor.getString(4));
            Set < String > set = new HashSet < >(labels1);
            labels1.clear();
            labels1.addAll(set);
        } while ( cursor . moveToNext ());
    }

    // Closing connection
    cursor.close();
    db.close();

    // Returning lables
    return labels1;
}

会有多个客户,每个客户可能有多个手,所以我希望第二个微调器仅显示与第一个微调器中选择的客户相关的那些手。

1 个答案:

答案 0 :(得分:0)

我建议使用Cursor's和Cursor适配器,这可以使事情变得更简单:-

  • 不需要中间数组(您的问题之一是String数组不能提供足够的信息)
  • CursorAdapters 设计用于处理 id (可满足以下要求:游标中的列名称为 _id (请参见 BaseColumns._ID 下面))。

以下是宽松地基于您的要求的相关微调器的基本示例。

首先DatbaseHelper DatabaseHelper.java

定义/创建了两个表Customers and Lots,分别为每个表添加数据的方法和从每个表中提取列表的方法都存在。提取的批次基于他们参考/所属/关联的客户。

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "mydb";
    public static final int DBVERSION = 1;
    public static final String TBL_CUSTOMER = "customer";
    public static final String TBL_LOT = "lot";


    public static final String COL_CUSTOMER_ID = BaseColumns._ID; //<<<<<<<<<< column name is _id (needed for Cursor Adapter)
    public static final String COL_CUSTOMER_NAME = "customer_name";

    public static final String COL_LOT_ID = BaseColumns._ID; //<<<<<<<<<< column name is _id (needed for Cursor Adapter)
    public static final String COL_LOT_NAME = "lot_name";
    public static final String COL_LOT_CUSTOMERREFERENCE = "customer_refererence";

    SQLiteDatabase mDB;

    public DatabaseHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
        mDB = this.getWritableDatabase(); //<<<<<<<<<< get the database connection (force create when constructing helper instance)
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String crt_customer_table_sql = "CREATE TABLE IF NOT EXISTS " + TBL_CUSTOMER + "(" +
                COL_CUSTOMER_ID + " INTEGER PRIMARY KEY, " +
                COL_CUSTOMER_NAME + " TEXT UNIQUE " +
                ")";

        String crt_lot_table_sql = "CREATE TABLE IF NOT EXISTS " + TBL_LOT + "(" +
                COL_LOT_ID + " INTEGER PRIMARY KEY, " +
                COL_LOT_NAME + " TEXT, " +
                COL_LOT_CUSTOMERREFERENCE + " INTEGER " +
                /*?????????? OPTIONAL IF FOREIGN KEYS ARE TURNED ON
                "REFERENCES " + TBL_CUSTOMER + "(" +
                COL_CUSTOMER_ID +
                ")" +
                */
                ")";
        db.execSQL(crt_customer_table_sql);
        db.execSQL(crt_lot_table_sql);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public long addCustomer(String name) {
        ContentValues cv = new ContentValues();
        cv.put(COL_CUSTOMER_NAME,name);
        return mDB.insert(TBL_CUSTOMER,null,cv);
    }

    public long addLot(String name, long customer_reference) {
        ContentValues cv = new ContentValues();
        cv.put(COL_LOT_NAME,name);
        cv.put(COL_LOT_CUSTOMERREFERENCE,customer_reference);
        return mDB.insert(TBL_LOT,name,cv);
    }

    public Cursor getCustomers() {
        return mDB.query(TBL_CUSTOMER,null,null,null,null,null,COL_CUSTOMER_NAME);
    }

    public Cursor getLotsPerCustomer(long customer_id) {
        String whereclause = COL_LOT_CUSTOMERREFERENCE + "=?";
        String[] whereargs = new String[]{String.valueOf(customer_id)};
        return mDB.query(TBL_LOT,null,whereclause,whereargs,null,null,COL_LOT_NAME);
    }
}
  • 请注意,以上内容非常简单。但是,显然需要对其进行调整以适合您的应用程序。

第二个代码是利用以上内容并结合2个链接/相关微调器的活动,其中,根据与当前选定客户相关的那些手数,可选择手数。

该活动使用的布局非常基本,只有两个微调框。微调器使用库存的Simple_List_Item_2布局(已使用2来查看所有重要的ID(通常不会向用户显示该ID))。

简而言之,每当在客户微调器中进行选择时,都会根据用于选择相关/参考批次的客户ID管理(设置或刷新)批次微调器。

public class MainActivity extends AppCompatActivity {

    Context mContext;
    DatabaseHelper mDBHlpr;
    SimpleCursorAdapter mCustomerSCA, mLotSCA;
    Spinner mCustomerList, mLotList;
    Cursor mCustomers, mLots;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        mDBHlpr = new DatabaseHelper(this);
        mCustomerList = this.findViewById(R.id.customer_list);
        mLotList = this.findViewById(R.id.lot_list);

        addTestingDataIfNoData(); //Go and add some testing data if there is none
        manageCustomerSpinner();
    }

    private void manageCustomerSpinner() {
        mCustomers = mDBHlpr.getCustomers();
        if (mCustomerSCA == null) {
            mCustomerSCA = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_2,
                    mCustomers,
                    new String[]{
                            DatabaseHelper.COL_CUSTOMER_NAME,
                            DatabaseHelper.COL_CUSTOMER_ID
                    },
                    new int[]{
                            android.R.id.text1,
                            android.R.id.text2
                    },
                    0
            );
            mCustomerList.setAdapter(mCustomerSCA);

            mCustomerList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    manageLotSpinner(id); //<<<<<<<<<< WHENEVER CUSTOMER IS SELECTED THE LOT SPINNER IS MANAGED >>>>>>>>>>
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
        } else {
            mCustomerSCA.swapCursor(mCustomers);
        }
    }

    private void manageLotSpinner(long id) {
        mLots = mDBHlpr.getLotsPerCustomer(id);
        if (mLotSCA == null) {
            mLotSCA = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_2,
                    mLots,
                    new String[]{
                            DatabaseHelper.COL_LOT_NAME,
                            DatabaseHelper.COL_LOT_ID
                    },
                    new int[]{
                            android.R.id.text1,
                            android.R.id.text2
                    },
                    0
            );
            mLotList.setAdapter(mLotSCA);
        } else {
            mLotSCA.swapCursor(mLots);
        }
    }


    private void addTestingDataIfNoData() {
        if (DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DatabaseHelper.TBL_CUSTOMER) < 1) {
            mDBHlpr.addCustomer("Fred");
            mDBHlpr.addCustomer("Mary");
            mDBHlpr.addCustomer("Sue");
            mDBHlpr.addCustomer("Alan");

            mDBHlpr.addLot("Lot001",2); // Lot for mary
            mDBHlpr.addLot("Lot002",1); // Lot for fred
            mDBHlpr.addLot("Lot003",4); // Lot for ala
            mDBHlpr.addLot("Lot004",3); // Lot for sue
            mDBHlpr.addLot("Lot005",3); // Lot for sue
            mDBHlpr.addLot("Lot006",3); // Lot for use
            mDBHlpr.addLot("Lot007",2); // Lot for mary
            mDBHlpr.addLot("Lot008",2); // Lot for mary
            mDBHlpr.addLot("Lot009",2); // Lot for mary
            mDBHlpr.addLot("Lot0010",2); // Lot for mary
            mDBHlpr.addLot("Lot0020",1); // Lot for Fred
            mDBHlpr.addLot("Lot00130",4); // Lot for Alan
            mDBHlpr.addLot("Lot00130",3); // Lot for Sue
        }
    }
}  

结果示例

初始

enter image description here

  • 由于排序顺序,Alan是最初的选择

选择玛丽后

enter image description here

  • 注意所使用的批号确实不适合排序