ソースを参照

Refactored SQLiteDataRepository.

Cristian Tanas 11 年 前
コミット
c7d18e111d

+ 28 - 4
PersistentDataSQLite/src/org/uab/android/persistentdata/sqlite/CoursesListActivity.java

@@ -14,15 +14,22 @@ public class CoursesListActivity extends ListActivity {
 	private static final int		COURSE_NEW_REQUEST_CODE = 1;
 	
 	SimpleCursorAdapter		coursesListAdapter;
-	SQLiteDataRepository 	sqliteDatabase;
+	SQLiteDataRepository 	repository;
 
 	@Override
 	protected void onCreate(Bundle savedInstanceState) {
 		super.onCreate(savedInstanceState);
 		
-		sqliteDatabase = new SQLiteDataRepository(this);
-		Cursor allCourses = sqliteDatabase.fetchAllCourses();
+		// Obtain a reference to the SQLiteDataRepository
+		repository = new SQLiteDataRepository(this);
 		
+		// Open the database for reading
+		repository.openDatabaseForReadOnly();
+		
+		// Get all courses from the database
+		Cursor allCourses = repository.fetchAllCourses();
+		
+		// Create a new Cursor adapter for the courses list
 		coursesListAdapter = new SimpleCursorAdapter(
 				this, 
 				R.layout.courses_list, 
@@ -31,6 +38,7 @@ public class CoursesListActivity extends ListActivity {
 				new int[] { R.id.courseName, R.id.courseCredits }, 
 				0);
 		
+		// Set the list adapter to the SimpleCursorAdapter created
 		setListAdapter(coursesListAdapter);
 	}
 	
@@ -47,6 +55,7 @@ public class CoursesListActivity extends ListActivity {
 		
 		switch ( item.getItemId() ) {
 		case R.id.addNewCourse:
+			// If the user select to add a new course start the form Activity for result
 			Intent addNewCourseIntent = new Intent(this, CoursesNewFormActivty.class);
 			startActivityForResult(addNewCourseIntent, COURSE_NEW_REQUEST_CODE);
 			return true;
@@ -60,11 +69,26 @@ public class CoursesListActivity extends ListActivity {
 	@Override
 	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 		
+		// Check the result from the CourseNewFormActivity
 		if ( resultCode == RESULT_OK && requestCode == COURSE_NEW_REQUEST_CODE ) {
 			
-			Cursor allCourses = sqliteDatabase.fetchAllCourses();
+			// Requery the repository for a list of all courses
+			Cursor allCourses = repository.fetchAllCourses();
+			
+			// Replace the Cursor in the list's adapter
 			coursesListAdapter.changeCursor(allCourses);
+			
+			// Notify the list adapter that it must refresh itself
 			coursesListAdapter.notifyDataSetChanged();
 		}
 	}
+	
+	@Override
+	protected void onDestroy() {
+		
+		// Release database resources
+		repository.release();
+		
+		super.onDestroy();
+	}
 }

+ 27 - 1
PersistentDataSQLite/src/org/uab/android/persistentdata/sqlite/CoursesNewFormActivty.java

@@ -23,6 +23,8 @@ public class CoursesNewFormActivty extends Activity {
 	
 	private static final String 		LOG_TAG = "PERSISTENT_DATA_SQLITE_COURSE_NEW_FORM_ACTIVITY";
 	
+	private SQLiteDataRepository sqliteDatabase;
+	
 	AutoCompleteTextView	classesAutoCompleteTextView;
 	EditText				numberOfCreditsEditText;
 	TextView				defaultHourTextView;
@@ -37,6 +39,9 @@ public class CoursesNewFormActivty extends Activity {
 		super.onCreate(savedInstanceState);
 		setContentView(R.layout.activity_main);
 		
+		// Obtain an instance of the SQLiteDataRepository
+		sqliteDatabase = new SQLiteDataRepository(this);
+		
 		// Get a reference to the UI element
 		classesAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.classAutoComplete);
 		
@@ -74,30 +79,49 @@ public class CoursesNewFormActivty extends Activity {
 		defaultHourTextView = (TextView) findViewById(R.id.defaultHourLabel);
 		
 		saveButton = (Button) findViewById(R.id.saveButton);
+		
+		// Set an OnClickListener for the SAVE button
 		saveButton.setOnClickListener(new OnClickListener() {
 			
 			@Override
 			public void onClick(View v) {
 				
+				// Get the values from the form's inputs
 				String courseName = classesAutoCompleteTextView.getText().toString();
 				int numberOfCredits = Integer.parseInt(numberOfCreditsEditText.getText().toString());
 				String checkBoxState = checkBoxStateMap.keySet().toString();
 				String hour = defaultHourTextView.getText().toString();
 				
-				SQLiteDataRepository sqliteDatabase = new SQLiteDataRepository(CoursesNewFormActivty.this);
+				// Open the database for writing
+				sqliteDatabase.openDatabaseForWrite();
+				
+				// Save the form data into the database
 				sqliteDatabase.saveCourse(courseName, numberOfCredits, checkBoxState, hour);
 				
 				Log.i(LOG_TAG, "Saved " + 
 						courseName + " " + numberOfCredits + " " + checkBoxState + " "+ hour + 
 						" to database.");
 				
+				// Clear the form's inputs
 				clearForm();
+				
+				// Set the result for the calling Activity
 				setResult(RESULT_OK);
 				finish();
 			}
 		});
 	}
 	
+	@Override
+	protected void onDestroy() {
+		
+		// Release the database resources
+		this.sqliteDatabase.release();
+		
+		super.onDestroy();
+	}
+	
+	// Resets the form's input Views
 	private void clearForm() {
 		
 		classesAutoCompleteTextView.setText("");
@@ -112,8 +136,10 @@ public class CoursesNewFormActivty extends Activity {
 		defaultHourTextView.setText(R.string.default_hour_label);
 	}
 	
+	// Called when the user clicks on one of the CheckBoxes, changing it's state
 	public void onCheckBoxClicked(View v) {
 		
+		// Save the ID of the CheckBox jointly with it's current state
 		CheckBox cb = (CheckBox) v;
 		checkBoxStateMap.put(cb.getId(), cb.isChecked());
 		

+ 7 - 0
PersistentDataSQLite/src/org/uab/android/persistentdata/sqlite/DatabaseOpenHelper.java

@@ -6,9 +6,11 @@ import android.database.sqlite.SQLiteOpenHelper;
 
 public class DatabaseOpenHelper extends SQLiteOpenHelper {
 	
+	// Variable holding the name of the database to be created
 	private static final String		DATABASE_NAME = "courses";
 	private static final int		DATABASE_VERSION = 1;
 	
+	// Variables holding the name of the table and columns to be created
 	static final String		COURSES_TABLE_NAME = "ASIGNATURAS";
 	static final String		_ID = "_id";
 	static final String		COURSE_NAME = "asignatura";
@@ -16,6 +18,7 @@ public class DatabaseOpenHelper extends SQLiteOpenHelper {
 	static final String		COURSE_DAYS_OF_WEEK = "dias";
 	static final String		COURSE_STARTS_AT = "hora";
 	
+	// Static variable containing the name of all the table's columns
 	static final String[] COLUMNS = {
 		_ID,
 		COURSE_NAME,
@@ -24,6 +27,7 @@ public class DatabaseOpenHelper extends SQLiteOpenHelper {
 		COURSE_STARTS_AT
 	};
 	
+	// Variable holding the SQL instruction to create a new table 
 	private static final String CREATE_COURSES_TABLE = 
 			"CREATE TABLE " + COURSES_TABLE_NAME + "( " +
 					_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
@@ -32,16 +36,19 @@ public class DatabaseOpenHelper extends SQLiteOpenHelper {
 					COURSE_DAYS_OF_WEEK + " TEXT, " +
 					COURSE_STARTS_AT + " TEXT)";
 	
+	// Public constructor. Delegates the construction to the SQLiteOpenHelper class
 	public DatabaseOpenHelper(Context context) {
 		super(context, DATABASE_NAME, null, DATABASE_VERSION);
 	}
 
+	// Create and initialize the database if not present
 	@Override
 	public void onCreate(SQLiteDatabase db) {
 		
 		db.execSQL(CREATE_COURSES_TABLE);
 	}
 
+	// Update the database if any changes have occurred (changes in the version number)
 	@Override
 	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 		// TODO Auto-generated method stub

+ 59 - 6
PersistentDataSQLite/src/org/uab/android/persistentdata/sqlite/SQLiteDataRepository.java

@@ -3,16 +3,48 @@ package org.uab.android.persistentdata.sqlite;
 import android.content.ContentValues;
 import android.content.Context;
 import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
 
 public class SQLiteDataRepository {
 	
-	private DatabaseOpenHelper		databaseOpenHelper;
+	// Helper object to obtain a reference to the database
+	private DatabaseOpenHelper databaseOpenHelper;
+	
+	// Reference to the SQLiteDatabase to store and retrieve data
+	private SQLiteDatabase				sqliteDatabase;
 
+	// Private constructor for the SQLiteDataRepository class
+	// Creates a new DatabaseOpenHelper object and holds a reference to the actual database
 	public SQLiteDataRepository(Context context) {
 		
 		this.databaseOpenHelper = new DatabaseOpenHelper(context);
 	}
 	
+	/**
+	 * Opens the database for read-only operations
+	 */
+	public void openDatabaseForReadOnly() {
+		
+		this.sqliteDatabase = this.databaseOpenHelper.getReadableDatabase();
+	}
+	
+	/**
+	 * Opens the database for read and write operations
+	 */
+	public void openDatabaseForWrite() {
+		
+		this.sqliteDatabase = this.databaseOpenHelper.getWritableDatabase();
+	}
+	
+	/**
+	 * Saves the information for a particular course.
+	 * 
+	 * @param courseName Name of the course.
+	 * @param numberOfCredits Number of credits of the course.
+	 * @param checkBoxState String identifying the state of the 
+	 * 						days of the week check boxes.
+	 * @param hour Starting hour for the course.
+	 */
 	public void saveCourse(String courseName, int numberOfCredits, 
 			String checkBoxState, String hour) {
 		
@@ -22,19 +54,25 @@ public class SQLiteDataRepository {
 		values.put(DatabaseOpenHelper.COURSE_DAYS_OF_WEEK, checkBoxState);
 		values.put(DatabaseOpenHelper.COURSE_STARTS_AT, hour);
 		
-		this.databaseOpenHelper.getWritableDatabase().insert(
+		this.sqliteDatabase.insert(
 				DatabaseOpenHelper.COURSES_TABLE_NAME, 
 				null, 
 				values);
 	}
 	
+	/**
+	 * Returns a specific course based on its ID.
+	 * 
+	 * @param courseId The unique course ID.
+	 * 
+	 * @return An iterator over the obtained registers.
+	 */
 	public Cursor fetchCourseById(int courseId) {
 		
 		String selection = DatabaseOpenHelper._ID + " = ?";
 		String[] selectionArgs = new String[] { String.valueOf(courseId) };
 		
-		Cursor result = this.databaseOpenHelper.getReadableDatabase()
-				.query(
+		Cursor result = this.sqliteDatabase.query(
 						DatabaseOpenHelper.COURSES_TABLE_NAME, 
 						DatabaseOpenHelper.COLUMNS, 
 						selection, 
@@ -45,10 +83,14 @@ public class SQLiteDataRepository {
 		return result;
 	}
 	
+	/**
+	 * Returns all saved courses.
+	 * 
+	 * @return An iterator over the list of courses from the database.
+	 */
 	public Cursor fetchAllCourses() {
 		
-		Cursor result = this.databaseOpenHelper.getReadableDatabase()
-				.query(
+		Cursor result = this.sqliteDatabase.query(
 						DatabaseOpenHelper.COURSES_TABLE_NAME, 
 						DatabaseOpenHelper.COLUMNS, 
 						null, 
@@ -58,4 +100,15 @@ public class SQLiteDataRepository {
 						null);
 		return result;
 	}
+	
+	/**
+	 * Release the database resources
+	 */
+	public void release() {
+		
+		if ( sqliteDatabase != null ) {
+			sqliteDatabase.close();
+			sqliteDatabase = null;
+		}
+	}
 }