Sunday, May 18, 2014

Database and Spinner Lists

   

The fuel mileage app I am working on has a SQLite database to store the vehicle data and the app also has a Spinner for selecting vehicles. My problem was retrieving a list of unique vehicles names in the database for the spinner. From what I knew I had two options, 

One: Step through the database to add names to an array while comparing  names already in the array.

Two: create a separate file of just the names such as vehiclelist.txt

Option one seemed a bit complicated. Option two I had done before in another app so I thought I could easily adapt it to this app.

  Frankly it became a headache trying to get it to work. I put the app off to the side in frustration. Then one morning I awoke with a thought that SQLite had to have some way of doing the task. I did a bit of research on the subject. The hard part was phrasing the question in Google search.

The Key to the task I needed to do was this SQLite search argument "SELECT DISTINCT".



public String[] returnVehicleList() {
// for returning a list of vehicles in database

String ADD_VEHICLE = "Add Vehicle";
String SELDIST = "SELECT DISTINCT " + KEY_VEHICLE_NAME + "   FROM " + TABLE_VEHICLES;

SQLiteDatabase databaseRead = this.getReadableDatabase();

// Cursor to point to rows
Cursor cursor = databaseRead.rawQuery(SELDIST, null);

// step thru database, get row data, assign data to string
String name;
ArrayList<String> list = new ArrayList<String>();

while (cursor.moveToNext()) {
// get the values in the row
name = cursor.getString(cursor.getColumnIndex
                (KEY_VEHICLE_NAME));
list.add(name);
}
list.add(ADD_VEHICLE);

cursor.close();
databaseRead.close();

// convert ArrayList to Array and return
String[] vehicleList = new String[list.size()];
vehicleList = list.toArray(vehicleList);

// return must be String array
return vehicleList;

}

Another problem I had on some devices is that some of the textEdit boxes were covered up by the softkeyboard, which I was able to fix by including this in the manifest android:windowSoftInputMode="adjustResize" as well as making the activity a scrollView.

I also changed the icon.


10,000 hour to Mastery.
10,000 - 587.5 = 9412.75hours left