I’m in a mobile programming course right now and we need to create a simple application where the user fills out a form and we take that data and record it in our own custom SQLite db. I’ve successfully made the form activity, with extensive error checking, and the ContentProvider to handle the database stuff. I’m pretty much completed, everything works right. I’m just struggling to add in this one last requirement- before we let the user submit his data for the form, we need to query the database and check if the username he’s adding already exists. If so, we notify him and don’t allow the database to be updated/created.
He’s some stuff from my content provider that describes the database:
public final static String DBNAME = "FormStorage";
public static final String AUTHORITY = "com.connor.black.provider";
public final static String TABLE_NAMESTABLE = "formstable";
private static UriMatcher sUriMatcher;
public final static String COLUMN_FIRSTNAME = "FirstName";
public final static String COLUMN_LASTNAME = "LastName";
public final static String COLUMN_PHONE = "PhoneNumber";
public final static String COLUMN_EMAIL = "Email";
public final static String COLUMN_USERNAME = "Username";
public final static String COLUMN_PASSWORD = "Password";
public final static String COLUMN_GENDER = "Gender";
public final static String COLUMN_COUNTRY = "Country";
public static final Uri CONTENT_URI = Uri.parse("content://com.connor.black.provider/" + TABLE_NAMESTABLE);
private static final String SQL_CREATE_MAIN = "CREATE TABLE " + TABLE_NAMESTABLE + "("+"_ID INTEGER PRIMARY KEY, "+
"FirstName TEXT, " +
"LastName TEXT, " +
"PhoneNumber TEXT, " +
"Email TEXT, " +
"Username TEXT, " +
"Password TEXT, " +
"Gender TEXT, " +
"Country TEXT)";
From my activity, in the submit onclicklister I’m doing this:
final Cursor mCursor;
submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Boolean submitCheck = true;
//...and code goes by....//
//Username duplicate check
String[] mProjection = new String[]{"FormStorage.formstable.Username"};
mCursor = getContentResolver().query(MyContentProvider.CONTENT_URI,
mProjection, null, null, null);
if(mCursor != null) {
if(mCursor.getCount() > 0) {
// Check if username already exists
}
}
So my question:
What should my mProjection string look like? I know the one I currently have is wrong, but I’m confused as to what the selection string should be?
Your projection is a
String[]that holds column names as its elements. They should not contain any info about the particular tables. Note that it is the Uri’s job to identify the table (using thesetTablemethod in your content provider’squeryimplementation).You should put your column values in a
String[]and have them replace the?in your selectionString. This will protect your database from nasty SQL injections.Then perform the query with,
Unless your table is small, you should be sure to perform the query on a separate thread. This will ensure that the UI thread isn’t blocked.