简体   繁体   中英

How to use HashMap for this scenario?

Given the client requirement task to do.

• Create Vehicle class which includes vehicle Id(Integer) as vehicle number and lot(Integer) as parking lot number. Implement getId() and getLot() that returns vehicle Id and Lot.

Create ParkingLot class that includes parkedVehicle, vehicle_lot_data and which implements the following

HashMap<Integer, Vehicle> parkedVehicle = new HashMap<>(); 
HashMap<Integer, Integer> vehicle_lot_data = new HashMap<>(); 

• parkVehicle(Vehicle, lot) parks vehicle at the lot, check for valid parking, also check that same vehicle is not allowed to park at multiple lots. Return “Lot already taken” if lot already booked by someone and “Vehicle already present” if we are trying to book multiple lots for the same vehicle. • isLotBooked(int lot) return boolean - It checks for the lot which is already booked. Return False for an empty lot and True for the booked lot. • isVehicleExists(int vehicleId) return boolean - It checks for already existing vehicle. Return True if the vehicle exists else False for the non-existing vehicle.

STEP 3: (Database.java)

Create a class Database to store parking lot data.

Create a local SQLite database (parking_database.db) • Create DATABASE_NAME variable and store parking_database.db. • Implement onCreate, onUpgrade for database creation and database drop. • ParkVehicle(Vehicle) - save parked vehicle to database. • getParkedVehicle(), getParkedVehicle(int vehicleId) - get all parked vehicles return ( Cursor ) • getAllBookedLots() - get all booked parking lots return ( Cursor )

Design table with the following schema

CREATE TABLE parking_lots (id integer PRIMARY KEY, 
lot_number INTEGER, 
vehicle_number INTEGER UNIQUE); 

• Implement ParkVehicleNow() that will get user input data from view, and store the data in these variables vehicle_id_field_txt and vehicle_lot_number_field_txt that will call park(int vehicle_id_field_txt, int vehicle_lot_number_field_txt) function internally. • park(int vehicle_id_field_txt, int vehicle_lot_number_field_txt) - will make use of ParkingLot class and park the vehicle using ParkingLot instance pl and save that vehicle to database using Databaseclass instance db. • If you are unable to park then make a Toast “Vehicle Already Parked choose a different lot or vehicle” else “Vehicle Parked” message will be Toasted. • Also, don't forget to perform validation for “Lot already taken” and “Vehicle already present” then don't park vehicle.

But I am not getting Step 2 how to implement the hashmap in ParkingLot.

What I tired is, here based on the scenario, I am not able to use the hashmap anywhere.

public class ParkingLot {
    HashMap<Integer, Vehicle> parkedVehicle = new HashMap<>();
    HashMap<Integer, Integer> vehicle_lot_data = new HashMap<>();

    public boolean isLotBooked(int lot, Context context) {
        Database db = new Database(context);
        return db.isAlreadyLotsExists(String.valueOf(lot));
    }

    public boolean isVehicleExists(int vehicleId, Context context) {
        Database db = new Database(context);
        return db.isAlreadyVehicleExists(String.valueOf(vehicleId));
    }

}


  public Vehicle(){

    }

    public Vehicle(int primaryId,int id, int lot){
        this.id = id;
        this.lot = lot;
        this.primaryId = primaryId;
    }
    public Vehicle(int id, int lot){
        this.id = id;
        this.lot = lot;
    }
    public int id;

    public int getPrimaryId() {
        return primaryId;
    }

    public void setPrimaryId(int primaryId) {
        this.primaryId = primaryId;
    }

    public int primaryId;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getLot() {
        return lot;
    }

    public void setLot(int lot) {
        this.lot = lot;
    }

    public int lot;

}


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Database db = new Database(this);
        db.ParkVehicle(new Vehicle(1000,1));
        db.ParkVehicle(new Vehicle(2000,2));

        // Reading all contacts
        Log.e("Reading: ", "Reading all contacts..");
        List<Vehicle> contacts = db.getParkedVehicle(); //all parked vehicle
        List<String> bookedSlots = db.getAllBookedLots(); //all booked slots

        for (Vehicle cn : contacts) {
            String log = "Id: " + cn.getPrimaryId() + " ,Vehicle: " + cn.getId() + " ,Lot: " +
                    cn.getLot();
            // Writing Contacts to log
            Log.e("ContactsAllVehicles: ", log);
        }

        for (String cn : bookedSlots) {
            // Writing Contacts to log
            Log.e("ContactsSlots: ", cn);
        }

        Vehicle vehicle= db.getParkedVehicle(1);
        Log.e("ContactsLots",""+vehicle.getId());

        //checking if lots already exisitng..
        boolean alreadyExist=db.isAlreadyLotsExists("0");
        Log.e("contactsslotsTest",""+alreadyExist);
    }



public class Database extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "vehicles";
    private static final String KEY_ID = "id";
    private static final String LOT_NUMBER = "lot_number";
    private static final String VEHICLE_NUMBER = "vehicle_number";
    private static final String PARKING_LOTS = "parking_lots"; //table name

    public Database(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        //3rd argument to be passed is CursorFactory instance
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + PARKING_LOTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + LOT_NUMBER + " INTEGER,"
                + VEHICLE_NUMBER + " INTEGER UNIQUE" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + PARKING_LOTS);

        // Create tables again
        onCreate(db);
    }

    void ParkVehicle(Vehicle contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(LOT_NUMBER, contact.getLot()); // Lot number
        values.put(VEHICLE_NUMBER, contact.getId()); // Vehicle number

        // Inserting Row
        db.insert(PARKING_LOTS, null, values);
        //2nd argument is String containing nullColumnHack
        db.close(); // Closing database connection
    }

    Vehicle getParkedVehicle(int id) { //single vehicle
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(PARKING_LOTS, new String[]{KEY_ID,
                        LOT_NUMBER, VEHICLE_NUMBER}, KEY_ID + "=?",
                new String[]{String.valueOf(id)}, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Vehicle contact = new Vehicle(Integer.parseInt(cursor.getString(0)),
                Integer.parseInt(cursor.getString(1)), Integer.parseInt(cursor.getString(2)));
        // return contact
        return contact;
    }

    public List<Vehicle> getParkedVehicle() {
        List<Vehicle> contactList = new ArrayList<Vehicle>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + PARKING_LOTS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Vehicle contact = new Vehicle();
                contact.setPrimaryId(Integer.parseInt(cursor.getString(0)));
                contact.setLot(Integer.parseInt(cursor.getString(1)));
                contact.setId(Integer.parseInt(cursor.getString(2)));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }

        // return contact list
        return contactList;
    }

    public List<String> getAllBookedLots(){
        List<String> contactList = new ArrayList<>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + PARKING_LOTS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        cursor.moveToFirst();

        // looping through all rows and adding to list
        if (cursor!=null && cursor.moveToFirst()) {
            while(cursor.isAfterLast() == false){
                contactList.add(cursor.getString(cursor.getColumnIndex(LOT_NUMBER)));
                Log.d("contactslotnumber",contactList.toString());

                cursor.moveToNext();
            }}
        return contactList;
    }

    public boolean isAlreadyLotsExists(String name){
            SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
            String query="SELECT * FROM "+PARKING_LOTS+" WHERE "+LOT_NUMBER+" = "+name;
            Cursor cursor = sqLiteDatabase.rawQuery(query,null);
            if(cursor.getCount()>0)
                return true;
            else
                return false;

    }

    public boolean isAlreadyVehicleExists(String name){
        SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
        String query="SELECT * FROM "+PARKING_LOTS+" WHERE "+VEHICLE_NUMBER+" = "+name;
        Cursor cursor = sqLiteDatabase.rawQuery(query,null);
        if(cursor.getCount()>0)
            return true;
        else
            return false;

    }

        // return contact list



    public int updateContact(Vehicle contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(LOT_NUMBER, contact.getLot());
        values.put(VEHICLE_NUMBER, contact.getId());

        // updating row
        return db.update(PARKING_LOTS, values, KEY_ID + " = ?",
                new String[]{String.valueOf(contact.getPrimaryId())});
    }

    // Deleting single contact
    public void deleteContact(Vehicle contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(PARKING_LOTS, KEY_ID + " = ?",
                new String[]{String.valueOf(contact.getPrimaryId())});
        db.close();
    }

    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + PARKING_LOTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }
}

This is what I done but there are some steps which are missing from the requirement. Say for eg: Step 2 I am not sure where to use the hashmap to use the parkVehicle method in ParkingLot class and similarly Step 4 too in MainActivity.

Probably hashmaps were given in the context of caching the DB data. When you write the vehicle/lot-related data, you use hashmaps as caches (utilizing write-back or write-through strategy, whichever matches your requirements or needs) and when you read the data, you always read them from hashmaps ie caches

Recall that write-back implies that you write the new data to cache but not DB (the data is written to DB at some later time) and write-through implies that whenever you write the new data, it is written to both cache and DB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM