import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DbAdapter {
/**
* Database fields
*/
public static final String KEY_ROWID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_URL = "url";
public static final String KEY_PRICE = "price";
/**
* Name of the table
*/
private static final String DATABASE_TABLE = "tobuy";
private SQLiteDatabase database;
private DbHelper dbHelper;
private Context context;
/**
* Constructor of this class.
* @param context
*/
public DbAdapter(Context context){
this.context = context;
}
/**
* This method get a connection to the database to query it.
* @return the same DbAdatper but with a connection to the database.
* @throws SQLException
*/
public DbAdapter open() throws SQLException{
dbHelper = new DbHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
/**
* This method close the database.
*/
public void close(){
dbHelper.close();
}
/**
* Create a new tobuy if the tobuy is successfully created return the new
* rowId for that note, otherwise return a -1 to indicate failure.
*/
public long createTobuy(String title,String url, String price){
ContentValues initialValues = createContentValues(title,url,price);
return database.insert(DATABASE_TABLE, null, initialValues);
}
/**
* Update the tobuy.
*/
public boolean updateTobuy(long rowId, String title, String url,
String price){
ContentValues updateValues = createContentValues(title,url,price);
return database.update(DATABASE_TABLE, updateValues, KEY_ROWID + "=" + rowId, null) > 0;
}
/**
* Delets tobuy
*/
public boolean deleteTobuy(long rowId){
return database.delete(DATABASE_TABLE,KEY_ROWID + "=" + rowId,null) > 0;
}
/**
* Return a Cursor over the list of all tobuy in the database
*
* @return Cursor over all notes
*/
public Cursor fetchAllTobuy(){
return database.query(DATABASE_TABLE, new String[]{KEY_ROWID,KEY_TITLE,KEY_URL,KEY_PRICE}, null, null, null, null, null);
}
/**
* Return a Cursor positioned at the defined tobuy
*/
public Cursor fetchToBuy(long rowId) throws SQLException{
Cursor mCursor = database.query(true, DATABASE_TABLE, new String[]{KEY_ROWID,KEY_TITLE,KEY_URL,KEY_PRICE},
KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
/**
* This method return a contentvalues with all the 3 information
* that we need to insert in the database.
*
* @param title title of the toBuy.
* @param url url of the toBuy (If It's an online object).
* @param price price of the toBuy.
* @return ContentValues with all the three parameters of the method.
*/
private ContentValues createContentValues(String title, String url,
String price) {
ContentValues values = new ContentValues();
values.put(KEY_TITLE,title);
values.put(KEY_URL,url);
values.put(KEY_PRICE,price);
return values;
}