DBContract.java
//Define the tables and columns of your local database
public final class DBContract {
/*Content Authority its a name for the content provider, is convenient to use the package app name to be unique on the device */
public static final String CONTENT_AUTHORITY = "com.yourdomain.yourapp";
//Use CONTENT_AUTHORITY to create all the database URI's that the app will use to link the content provider.
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
/*the name of the uri that can be the same as the name of your table.
this will translate to content://com.yourdomain.yourapp/user/ as a valid URI
*/
public static final String PATH_USER = "User";
// To prevent someone from accidentally instantiating the contract class,
// give it an empty constructor.
public DBContract () {}
//Intern class that defines the user table
public static final class UserEntry implements BaseColumns {
public static final URI CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_USER).build();
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE+"/"+CONTENT_AUTHORITY+"/"+PATH_USER;
//Name of the table
public static final String TABLE_NAME="User";
//Columns of the user table
public static final String COLUMN_Name="Name";
public static final String COLUMN_Password="Password";
public static Uri buildUri(long id){
return ContentUris.withAppendedId(CONTENT_URI,id);
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper{
//if you change the schema of the database, you must increment this number
private static final int DATABASE_VERSION=1;
static final String DATABASE_NAME="mydatabase.db";
private static DBHelper mInstance=null;
public static DBHelper getInstance(Context ctx){
if(mInstance==null){
mInstance= new DBHelper(ctx.getApplicationContext());
}
return mInstance;
}
public DBHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public int GetDatabase_Version() {
return DATABASE_VERSION;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase){
//Create the table users
final String SQL_CREATE_TABLE_USERS="CREATE TABLE "+UserEntry.TABLE_NAME+ " ("+
UserEntry._ID+" INTEGER PRIMARY KEY, "+
UserEntry.COLUMN_Name+" TEXT , "+
UserEntry.COLUMN_Password+" TEXT "+
" ); ";
sqLiteDatabase.execSQL(SQL_CREATE_TABLE_USERS);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + UserEntry.TABLE_NAME);
}
}
DBProvider.java
public class DBProvider extends ContentProvider {
private static final UriMatcher sUriMatcher = buildUriMatcher();
private DBHelper mDBHelper;
private Context mContext;
static final int USER = 100;
static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = DBContract.CONTENT_AUTHORITY;
matcher.addURI(authority, DBContract.PATH_USER, USER);
return matcher;
}
@Override
public boolean onCreate() {
mDBHelper = new DBHelper(getContext());
return false;
}
public PeaberryProvider(Context context) {
mDBHelper = DBHelper.getInstance(context);
mContext = context;
}
@Override
public String getType(Uri uri) {
// determine what type of Uri is
final int match = sUriMatcher.match(uri);
switch (match) {
case USER:
return DBContract.UserEntry.CONTENT_TYPE;
default:
throw new UnsupportedOperationException("Uri unknown: " + uri);
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Cursor retCursor;
try {
switch (sUriMatcher.match(uri)) {
case USER: {
retCursor = mDBHelper.getReadableDatabase().query(
DBContract.UserEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
}
default:
throw new UnsupportedOperationException("Uri unknown: " + uri);
}
} catch (Exception ex) {
Log.e("Cursor", ex.toString());
} finally {
mDBHelper.close();
}
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
final SQLiteDatabase db = mDBHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
Uri returnUri;
try {
switch (match) {
case USER: {
long _id = db.insert(DBContract.UserEntry.TABLE_NAME, null, values);
if (_id > 0)
returnUri = DBContract.UserEntry.buildUri(_id);
else
throw new android.database.SQLException("Error at inserting row in " + uri);
break;
}
default:
throw new UnsupportedOperationException("Uri unknown: " + uri);
}
mContext.getContentResolver().notifyChange(uri, null);
return returnUri;
} catch (Exception ex) {
Log.e("Insert", ex.toString());
db.close();
} finally {
db.close();
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
final SQLiteDatabase db = DBHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int deletedRows;
if (null == selection) selection = "1";
try {
switch (match) {
case USER:
deletedRows = db.delete(
DBContract.UserEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new UnsupportedOperationException("Uri unknown: " + uri);
}
if (deletedRows != 0) {
mContext.getContentResolver().notifyChange(uri, null);
}
return deletedRows;
} catch (Exception ex) {
Log.e("Insert", ex.toString());
} finally {
db.close();
}
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
final SQLiteDatabase db = mDBHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int updatedRows;
try {
switch (match) {
case USER:
updatedRows = db.update(DBContract.UserEntry.TABLE_NAME, values, selection, selectionArgs);
break;
default:
throw new UnsupportedOperationException("Uri unknown: " + uri);
}
if (updatedRows != 0) {
mContext.getContentResolver().notifyChange(uri, null);
}
return updatedRows;
} catch (Exception ex) {
Log.e("Update", ex.toString());
} finally {
db.close();
}
return -1;
}
}
How to Use:
public void InsertUser() {
try {
ContentValues userValues = getUserData("Jhon","XXXXX");
DBProvider dbProvider = new DBProvider(mContext);
dbProvider.insert(UserEntry.CONTENT_URI, userValues);
} catch (Exception ex) {
Log.e("Insert", ex.toString());
}
}
public ContentValues getUserData(String name, String pass) {
ContentValues userValues = new ContentValues();
userValues.put(UserEntry.COLUMN_Name, name);
userValues.put(UserEntry.COLUMN_Password, pass);
return userValues;
}