如何仅在 recyclerview 中显示具有特定值的数据

Posted

技术标签:

【中文标题】如何仅在 recyclerview 中显示具有特定值的数据【英文标题】:How can I display data in recyclerview only with specific value 【发布时间】:2021-05-14 05:31:49 【问题描述】:

我正在尝试使用 SQLite 数据库制作诸如存储汽车加油的日记之类的东西,但我不知道如何将可见数据仅限于分配给特定汽车 ID 的加油。

流程如下:(我们假设数据库中有数据)

点击特定汽车后,我会被重定向到汽车资料活动,在那里我可以看到有关该汽车的更多信息。 然后,在选择“记录加油”选项后,我将被重定向到我之前选择的汽车的记录加油的 recyclerview。

问题:

在从汽车配置文件输入列表后,我从“燃料”表中获取每一行,但我只想查看分配给这辆车的加油。

这是我在这个问题中的 3 项重要活动:

第一个是注册汽车列表 first activity

第二个是汽车资料 second activity

第三个是加油清单 third activity

(加油单上每一项末尾的数字是我来自并添加数据的汽车的ID)

DatabaseHelper.java

    public class DatabaseHelper extends SQLiteOpenHelper 

    private Context context;

    private static final String DATABASE_NAME = "CarsList.db";
    private static final int  DATABASE_VERSION = 1;

    private static final String TABLE_CARS = "cars";
    private static final String COLUMN_CAR_ID = "_id";
    private static final String COLUMN_BRAND = "car_brand";
    private static final String COLUMN_MODEL = "car_model";
    private static final String COLUMN_YEAR_MADE = "car_year_made";

    private static final String TABLE_FUELS = "fuels";
    private static final String COLUMN_FUEL_ID = "fuel_id";
    private static final String COLUMN_STATION_NAME = "station_name";
    private static final String COLUMN_FUEL_TYPE = "fuel_type";
    private static final String COLUMN_FUEL_AMOUNT = "fuel_amount";
    private static final String COLUMN_FUEL_COST = "fuel_cost";
    private static final String COLUMN_MILEAGE = "mileage";
    private static final String COLUMN_FUEL_DATE = "fuel_date";
    private static final String COLUMN_FUELED_CAR_ID = "fueled_car_id";

    public DatabaseHelper(@Nullable Context context) 
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    

    @Override
    public void onCreate(SQLiteDatabase db) 
        String query1 =
                "CREATE TABLE " + TABLE_CARS +
                        " (" + COLUMN_CAR_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        COLUMN_BRAND + " TEXT, " +
                        COLUMN_MODEL + " TEXT, " +
                        COLUMN_YEAR_MADE + " INTEGER);";
        String query2 =
                "CREATE TABLE " + TABLE_FUELS +
                        " (" + COLUMN_FUEL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        COLUMN_STATION_NAME + " TEXT, " +
                        COLUMN_FUEL_TYPE + " TEXT, " +
                        COLUMN_FUEL_AMOUNT + " INTEGER, " +
                        COLUMN_FUEL_COST + " INTEGER, " +
                        COLUMN_MILEAGE + " INTEGER, " +
                        COLUMN_FUEL_DATE + " TEXT, " +
                        COLUMN_FUELED_CAR_ID + " INTEGER REFERENCES "+ COLUMN_CAR_ID + ");";
        db.execSQL(query1);
        db.execSQL(query2);
    

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

    void addCar(String brand,
                String model,
                int yearMade
    ) 
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(COLUMN_BRAND, brand);
        cv.put(COLUMN_MODEL, model);
        cv.put(COLUMN_YEAR_MADE, yearMade);
        long result = db.insert(TABLE_CARS, null, cv);
        if (result == -1) 
            Toast.makeText(context, "Failed adding new car.", Toast.LENGTH_SHORT).show();
         else 
            Toast.makeText(context, "Added a new car!", Toast.LENGTH_SHORT).show();
        
    

    void addFuel(String stationName,
                 String fuelType,
                 int fuelAmount,
                 int fuelCost,
                 int mileage,
                 String fuelDate,
                 String fueledCarId
    ) 
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(COLUMN_STATION_NAME, stationName);
        cv.put(COLUMN_FUEL_TYPE, fuelType);
        cv.put(COLUMN_FUEL_AMOUNT, fuelAmount);
        cv.put(COLUMN_FUEL_COST, fuelCost);
        cv.put(COLUMN_MILEAGE, mileage);
        cv.put(COLUMN_FUEL_DATE, fuelDate);
        cv.put(COLUMN_FUELED_CAR_ID, fueledCarId);
        long result = db.insert(TABLE_FUELS, null, cv);
        if (result == -1) 
            Toast.makeText(context, "Failed adding new refueling.", Toast.LENGTH_SHORT).show();
         else 
            Toast.makeText(context, "Added a new refueling!", Toast.LENGTH_SHORT).show();
        
    

    @SuppressLint("Recycle")
    Cursor readAllCars() 
        String query = "SELECT * FROM " + TABLE_CARS;
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = null;
        if(db != null) 
            cursor = db.rawQuery(query, null);
        
        return cursor;
    

    @SuppressLint("Recycle")
    Cursor readAllFuels() 
        String query = "SELECT * FROM " + TABLE_FUELS;
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = null;
        if(db != null) 
            cursor = db.rawQuery(query, null);
        
        return cursor;
    

RecyclerFuelAdapter.java

    public class RecyclerFuelAdapter extends RecyclerView.Adapter<RecyclerFuelAdapter.MyViewHolder> 

    private ArrayList<String> fuelIds, stationNames, fuelTypes, fuelAmounts, fuelCosts, mileages, fuelDates, fueledCarIds;
    private Context context;
    public RecyclerViewClickListener listener;

    public RecyclerFuelAdapter(Context context,
                               ArrayList<String> fuelIds,
                               ArrayList<String> stationNames,
                               ArrayList<String> fuelTypes,
                               ArrayList<String> fuelAmounts,
                               ArrayList<String> fuelCosts,
                               ArrayList<String> mileages,
                               ArrayList<String> fuelDates,
                               ArrayList<String> fueledCarIds,
                               RecyclerViewClickListener listener) 
        this.fuelIds = fuelIds;
        this.stationNames = stationNames;
        this.fuelTypes = fuelTypes;
        this.fuelAmounts = fuelAmounts;
        this.fuelCosts = fuelCosts;
        this.mileages = mileages;
        this.fuelDates = fuelDates;
        this.fueledCarIds = fueledCarIds;
        this.context = context;
        this.listener = listener;
    

    @NonNull
    @Override
    public RecyclerFuelAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
        LayoutInflater inflater = LayoutInflater.from(context);
        View fuelView = inflater.inflate(R.layout.list_fuel, parent, false);
        return new MyViewHolder(fuelView);
    

    @Override
    public void onBindViewHolder(@NonNull RecyclerFuelAdapter.MyViewHolder holder, int position) 

        String $fuelAmount = fuelAmounts.get(position) + "L";
        String $fuelCost = fuelCosts.get(position) + "$";

        holder.fuelIdTv.setText(String.valueOf(fuelIds.get(position)));
        holder.fuelAmountTv.setText($fuelAmount);
        holder.fuelCostTv.setText($fuelCost);
        holder.fuelDateTv.setText(String.valueOf(fuelDates.get(position)));
        holder.fueledCarTv.setText(String.valueOf(fueledCarIds.get(position)));
    

    @Override
    public int getItemCount() 
        return fuelIds.size();
    

    public interface RecyclerViewClickListener 
        void onClick(View v, int position);
    

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener 

        private TextView fuelIdTv, fuelAmountTv, fuelCostTv, fuelDateTv, fueledCarTv;

        public MyViewHolder(@NonNull View view) 
            super(view);
            fuelIdTv = view.findViewById(R.id.fuelIdTv);
            fuelAmountTv = view.findViewById(R.id.fuelAmountTv);
            fuelCostTv = view.findViewById(R.id.fuelCostTv);
            fuelDateTv = view.findViewById(R.id.fuelDateTv);
            fueledCarTv = view.findViewById(R.id.fueledCarTv);

            view.setOnClickListener(this);
        

        @Override
        public void onClick(View v) 
            listener.onClick(v, getAdapterPosition());
        
    

FuelActivity.java

    public class FuelActivity extends AppCompatActivity 


    public static final String COLUMN_CAR_ID = "_id";
    private DatabaseHelper myDB;
    private RecyclerFuelAdapter.RecyclerViewClickListener listener;
    private ArrayList<String> fuelIds, stationNames, fuelTypes, fuelAmounts, fuelCosts, mileages, fuelDates, fueledCarIds;
    private RecyclerView recyclerView;
    private RecyclerFuelAdapter RecyclerFuelAdapter;
    private Button goToAddFuelBtn;

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

        recyclerView = findViewById(R.id.fuelRecycler);
        goToAddFuelBtn = findViewById(R.id.goToAddFuelBtn);

        Intent intent1 = getIntent();
        String value = intent1.getStringExtra(ProfileActivity.COLUMN_CAR_ID);

        goToAddFuelBtn.setOnClickListener(v -> 

            Intent intent4 = new Intent(getApplicationContext(), AddFuelActivity.class);
            intent4.putExtra(COLUMN_CAR_ID, value);
            startActivity(intent4);
        );

        myDB = new DatabaseHelper(FuelActivity.this);
        fuelIds = new ArrayList<>();
        stationNames = new ArrayList<>();
        fuelTypes = new ArrayList<>();
        fuelAmounts = new ArrayList<>();
        fuelCosts = new ArrayList<>();
        mileages = new ArrayList<>();
        fuelDates = new ArrayList<>();
        fueledCarIds = new ArrayList<>();

        storeFuelsInArrays();
        createAdapter();
    

    @Override
    public void onBackPressed()
    
        super.onBackPressed();
        startActivity(new Intent(FuelActivity.this, MainActivity.class));
        finish();

    
    private void createAdapter() 
        setOnClickListener();
        RecyclerFuelAdapter = new RecyclerFuelAdapter(FuelActivity.this, fuelIds, stationNames, fuelTypes, fuelAmounts, fuelCosts, mileages, fuelDates, fueledCarIds,  listener);
        recyclerView.setAdapter(RecyclerFuelAdapter);
        LinearLayoutManager layoutManager = new LinearLayoutManager(FuelActivity.this);
        recyclerView.setLayoutManager(layoutManager);
    

    private void setOnClickListener() 
        listener = (v, position) -> 
            Toast.makeText(getApplicationContext(), "clicked on " + fuelIds.get(position), Toast.LENGTH_SHORT).show();
        ;
    




    private void storeFuelsInArrays() 
        Cursor cursor = myDB.readAllFuels();
        if (cursor.getCount() == 0) 
            Toast.makeText(this, "No data to be displayed.", Toast.LENGTH_SHORT).show();
         else 
            while (cursor.moveToNext()) 
                fuelIds.add(cursor.getString(cursor.getColumnIndex("fuel_id")));
                stationNames.add(cursor.getString(cursor.getColumnIndex("station_name")));
                fuelTypes.add(cursor.getString(cursor.getColumnIndex("fuel_type")));
                fuelAmounts.add(cursor.getString(cursor.getColumnIndex("fuel_amount")));
                fuelCosts.add(cursor.getString(cursor.getColumnIndex("fuel_cost")));
                mileages.add(cursor.getString(cursor.getColumnIndex("mileage")));
                fuelDates.add(cursor.getString(cursor.getColumnIndex("fuel_date")));
                fueledCarIds.add(cursor.getString(cursor.getColumnIndex("fueled_car_id")));
            
        
    
 

ProfileActivity.java

    public class ProfileActivity extends AppCompatActivity 

    public static final String COLUMN_CAR_ID = "_id";
    private TextView myCarID, myCarBrand, myCarModel, myCarYear;
    private Button goToFuelList, goToServiceList;


    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile_activity);

        myCarID = findViewById(R.id.myCarID);
        myCarBrand = findViewById(R.id.myCarBrand);
        myCarModel = findViewById(R.id.myCarModel);
        myCarYear = findViewById(R.id.myCarYear);
        goToFuelList = findViewById(R.id.goToFuelList);
        goToServiceList = findViewById(R.id.goToServiceList);

        myCarID.setText(getCarsData(0));
        myCarBrand.setText(getCarsData(1));
        myCarModel.setText(getCarsData(2));
        myCarYear.setText(getCarsData(3));

        Intent intent = getIntent();
        String value = intent.getStringExtra(MainActivity.COLUMN_CAR_ID);

        goToFuelList.setOnClickListener(v -> 
            Intent intent1 = new Intent(getApplicationContext(), FuelActivity.class);
            intent1.putExtra(COLUMN_CAR_ID, value);
            startActivity(intent1);
        );
    

        @SuppressLint("Recycle")
        private String getCarsData(int option) 
            SQLiteDatabase db = this.openOrCreateDatabase("CarsList.db", Context.MODE_PRIVATE, null);
            Cursor cursor;
            if(db != null) 
                Intent intent = getIntent();
                String value = intent.getStringExtra(MainActivity.COLUMN_CAR_ID);
                cursor = db.rawQuery("SELECT _id,car_brand,car_model,car_year_made FROM cars WHERE _id = " + value, null);
                if (cursor.getCount() == 0) 
                    Toast.makeText(getApplicationContext(), "no data", Toast.LENGTH_SHORT).show();
                
                StringBuilder buffer = new StringBuilder();
                while (cursor.moveToNext()) 
                    switch (option) 
                        case 0: buffer.append(cursor.getString(0));
                        break;
                        case 1: buffer.append(cursor.getString(1));
                        break;
                        case 2: buffer.append(cursor.getString(2));
                        break;
                        case 3: buffer.append(cursor.getString(3));
                        break;
                    
                
                return buffer.toString();
            
            return null;
        
    

【问题讨论】:

【参考方案1】:

经过 3 天的尝试,我自己已经弄清楚了,所以如果有人遇到同样的问题,那就是显示依赖于另一个 recyclerview 的值的 recyclerview 数据,这对我来说是可行的方式,即使它可能不会做一个完美的人。

我只是从 Intent 内部的 SQLite 表中传递了存储“_id”列的值,并在将数据添加到 ArrayLists 时对其进行了检查。

FuelActivity.java

private void storeFuelsInArrays() 
    Cursor cursor = myDB.readAllFuels();
    Intent intent1 = getIntent();
    String checkedValue = intent1.getStringExtra(ProfileActivity.COLUMN_CAR_ID);
    
    if (cursor.getCount() == 0) 
        Toast.makeText(this, "No data to be displayed.", Toast.LENGTH_SHORT).show();
     else 
        while (cursor.moveToNext()) 
            String value = cursor.getString(cursor.getColumnIndex("fueled_car_id"));
            if (value.equals(checkedValue)) 
                fuelIds.add(cursor.getString(cursor.getColumnIndex("fuel_id")));
                stationNames.add(cursor.getString(cursor.getColumnIndex("station_name")));
                fuelTypes.add(cursor.getString(cursor.getColumnIndex("fuel_type")));
                fuelAmounts.add(cursor.getString(cursor.getColumnIndex("fuel_amount")));
                fuelCosts.add(cursor.getString(cursor.getColumnIndex("fuel_cost")));
                mileages.add(cursor.getString(cursor.getColumnIndex("mileage")));
                fuelDates.add(cursor.getString(cursor.getColumnIndex("fuel_date")));
                fueledCarIds.add(cursor.getString(cursor.getColumnIndex("fueled_car_id")));
            
        
    

如果有人知道更好的方法,如果你能把它们放在这里,我会很高兴。

【讨论】:

以上是关于如何仅在 recyclerview 中显示具有特定值的数据的主要内容,如果未能解决你的问题,请参考以下文章

如何在 RecyclerView 中选择和取消选择项目?如何仅在回收站视图中突出显示所选项目?

特定字体仅在 Firefox 中具有不正确的下划线 - 错误在哪里,如何解决?

仅在 mysql “show tables” 中显示具有特定模式的表

RecyclerView项的属性在使用DataBinding时自动更改

使用自定义适配器仅在recyclerview中的列表中显示前两项

仅在最大日期而不是在组的其他条目中显示具有特定值的组