Database doesn't save values using overloading methods - java

I can't understand why is the database either not saving the values I enter or is it the method which I am using to pull all the data not working correctly. It doesn't throw any errors it just doesn't work. Here is the code:
private static final String QUERY_TRIANGLE_CREATE_TABLE =
"CREATE TABLE " + TRIANGLE_TABLE_NAME + " (" + TRIANGLE_COL_ID + " INTEGER PRIMARY KEY, " +
TRIANGLE_VALUE_A + " TEXT, " + TRIANGLE_VALUE_C + "TEXT, " + TRIANGLE_VALUE_B + " TEXT, " + TRIANGLE_RESULT + " TEXT," + TRIANGLE_HISTORY_INFORMATION + " TEXT" + " );";
public void insertTriangleCalc(String a,String b, String c,String d,String e){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TRIANGLE_VALUE_A,a);
values.put(TRIANGLE_VALUE_B,b);
values.put(TRIANGLE_VALUE_C,c);
values.put(TRIANGLE_RESULT,d);
values.put(TRIANGLE_HISTORY_INFORMATION,e);
database.insert("triangle", null, values);
database.close();
}
public void insertTriangleCalc(String a,String b, String c,String d){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TRIANGLE_VALUE_A,a);
values.put(TRIANGLE_VALUE_B,b);
values.put(TRIANGLE_RESULT,c);
values.put(TRIANGLE_HISTORY_INFORMATION,d);
database.insert("triangle", null, values);
database.close();}
public List<Triangle> ObjectRead() {
List<Triangle> valuesList = new ArrayList<>();
String sql = "SELECT * FROM triangle ORDER BY id DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
int id = Integer.parseInt(cursor.getString(cursor.getColumnIndex("id")));
String valueA = cursor.getString(cursor.getColumnIndex("valueA"));
String valueB = cursor.getString(cursor.getColumnIndex("valueB"));
String valueC="0";
try {
} catch (Exception e){
}
String result = cursor.getString(cursor.getColumnIndex("result"));
String history = cursor.getString(cursor.getColumnIndex("history"));
Triangle triangle = new Triangle();
triangle.id = id;
triangle.valueA = valueA;
triangle.valueB = valueB;
triangle.valueC = valueC;
triangle.Result = result;
triangle.history = history;
valuesList.add(triangle);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return valuesList;
}
Can anyone have a look at it and help me figure out what am I not setting up properly. It works for public void insertTriangleCalc(String a,String b, String c,String d) , but not for public void insertTriangleCalc(String a,String b, String c,String d,String e).

Decided to check from top to bottom and the whole thing was happening because of a missing empty space TRIANGLE_VALUE_C + "TEXT, "
<- here. This has now been resolved and it can finally store data correctly.

Related

SQL - How to return a list of data

I have this SQL method below, it is suppose to return multiple rows of data, but it is only returning one item every time I try to display the data.
How do I fix that?
//Constant
public static final String COL_4 = "LikeSong";
//Database Table
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE UserInfo(ID INTEGER PRIMARY KEY AUTOINCREMENT, Users_Name TEXT, PlaylistName TEXT,likeAlbum TEXT,LikeSong TEXT)");
}
public String[] getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
String[] LikeSong = null;
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
LikeSong = note.split(",");
}
cursor.close();
db.close();
return LikeSong;
}
Inside the while loop in each iteration you change the value of LikeSong, so when the loop ends, LikeSong has the last value assigned to it.
I think that you want a list of arrays returned by your method getLikedSongs() like this:
public List<String[]> getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
List<String[]> list = new ArrayList<>();
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
LikeSong.add(note.split(","));
}
cursor.close();
db.close();
return LikeSong;
}
Okay...now I see. You are reassigning LikeSong for each iteration of the while loop and returning the String array after the while loop has completed. So obviously, you will get value of only the last row.

How to update a SQLite database in android?

I am trying to update an SQLite database table with an integer value.I have tried 2 approaches the first one does not update the table and the 2nd one gives an SQLiteException.
1st using the update method:-
public void updateBookQty(String quantity,String bookId)
{
SQLiteDatabase db = this.getWritableDatabase();
int updateQty = getQuantity(bookId) - Integer.parseInt(quantity) ;
ContentValues values = new ContentValues();
values.put(KEY_QTY,updateQty);
try{
db.update(BOOKS_TABLE, values, KEY_BOOK_ID+ " = ?",
new String[] { String.valueOf(bookId) });
Log.d("BookUpdate", String.valueOf(updateQty));
}catch (SQLException e)
{
Log.d("UpdateError",e.toString());
}
}
2nd using execSQL:-
public void updateQty(Integer qty,String bookId)
{
int originalQty = getQuantity(bookId);
int updateQty = originalQty - qty;
try{
SQLiteDatabase db = this.getWritableDatabase();
String rawQuery = "update "+BOOKS_TABLE+" set "+KEY_QTY+" = "+updateQty+ " where "+KEY_BOOK_ID+" = "+bookId+" ;" ;
db.execSQL(rawQuery);
db.close();
Log.v("UpdateQty", "Qty updated");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Here I get a SQLiteException:-
System.err: android.database.sqlite.SQLiteException: near "0000169":
syntax error (code 1): , while compiling: update books_table set
quantity = -10 where book_id = BK 0000169 ;
try this,
public void updateQty(Integer qty,String bookId)
{
int originalQty = getQuantity(bookId);
int updateQty = originalQty - qty;
try{
SQLiteDatabase db = this.getWritableDatabase();
String rawQuery = "update " + BOOKS_TABLE + " set " + KEY_QTY + " = " + updateQty + " where " + KEY_BOOK_ID + " = '" + bookId + "';";
db.execSQL(rawQuery);
db.close();
Log.v("UpdateQty", "Qty updated");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
As your id is string you must quote the value, esp. It contains space:
String rawQuery = "update "+BOOKS_TABLE
+ " set "+KEY_QTY+" = "+updateQty
+ " where "+KEY_BOOK_ID+" = '"+bookId+"';" ;

SQLite Database Upgrade Condition

I have an android Quote application in which I have used SQLite Database for storing quotes. I have launched the first version of the application with this DatabaseHelper.
public class DataBaseHandler extends SQLiteOpenHelper {
private static String DB_PATH;
private static String DB_NAME = "SuccessQuotes";
private SQLiteDatabase myDataBase;
private static int DATABASE_VERSION = 1;
private final Context myContext;
public DataBaseHandler(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
DB_PATH = context.getDatabasePath(DB_NAME).toString();
Log.e("path", DB_PATH);
}
// ==============================================================================
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// ==============================================================================
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
// ==============================================================================
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
// ==============================================================================
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
// ==============================================================================
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
// ==============================================================================
#Override
public void onCreate(SQLiteDatabase db) {
}
// ==============================================================================
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
and my Database Activity is :
public class DAO {
// All Static variables
private SQLiteDatabase database;
private DataBaseHandler dbHandler;
private static final String TABLE_QUOTES = "quotes";
private static final String TABLE_AUTHORS = "authors";
private static final String TABLE_SETTINGS = "settings";
// Pages Table Columns names
private static final String QU_ID = "_quid";
private static final String QU_TEXT = "qu_text";
private static final String QU_AUTHOR = "qu_author";
private static final String QU_FAVORITE = "qu_favorite";
private static final String QU_WEB_ID = "qu_web_id";
private static final String AU_ID = "_auid";
private static final String AU_NAME = "au_name";
private static final String AU_PICTURE = "au_picture";
private static final String AU_PICTURE_SDCARD = "au_picture_sdcard";
private static final String AU_WEB_ID = "au_web_id";
// ==============================================================================
public DAO(Context context) {
dbHandler = new DataBaseHandler(context);
try {
dbHandler.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbHandler.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
// Log.e("path2", context.getDatabasePath("SuccessQuotes").toString());
// open();
}
// ==============================================================================
// Getting All Quotes
public Cursor getQuotes(String start) {
// Select All Query
String limit = "15";
if (start.equals("5000")) {
String query_count = "SELECT COUNT(" + QU_ID + ") AS count FROM "
+ TABLE_QUOTES;
Cursor c_count = database.rawQuery(query_count, null);
c_count.moveToFirst();
Integer count = c_count.getInt(c_count.getColumnIndex("count"));
limit = String.valueOf(count);
}
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " ORDER BY " + QU_WEB_ID + " DESC "+ " LIMIT " + start + ", " + limit;
//Log.i("query",query);
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting All Quotes
public Cursor getFavoriteQuotes(String start) {
// Select All Query
String limit = "15";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_FAVORITE + " = " + "1"+" ORDER BY " + QU_WEB_ID + " DESC "+ " LIMIT " + start + ", " + limit;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
//======================================================================
// Getting Fav Quote from ID
public String getFavQuotes(String strkey_id) {
// Select All Query
String fav = "";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_FAVORITE + " = " + "1 AND " + QU_ID + " = " +strkey_id;
Cursor cursor = database.rawQuery(query, null);
if(cursor.getCount() != 0)
{
cursor.moveToFirst();
fav = cursor.getString(cursor.getColumnIndex(QU_FAVORITE));
}
return fav;
}
// ==============================================================================
// Getting All Author Quotes
public Cursor getAuthorQuotes(String authorID,String start) {
// Select All Query
String limit="15";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_AUTHOR + " = " + authorID + " ORDER BY "+ QU_WEB_ID +" DESC "+ " LIMIT " + start + ", " + limit;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting Selected Quote
public Cursor getOneQuote(String quoteID) {
// Select All Query
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_ID + " = '" + quoteID + "'";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
public void addOrRemoveFavorites(String id, String value) {
ContentValues values = new ContentValues();
values.put(QU_FAVORITE, value);
// Update Row
// database.update(TABLE_QUOTES, values, QU_ID + "=?", new String[] { id });
database.update(TABLE_QUOTES, values, QU_ID + "=?", new String[] { id });
}
// ==============================================================================
// Getting All Authors
public Cursor getAllAuthors() {
// Select All Query
String query = "SELECT *, COUNT(" + QU_AUTHOR + ") AS count FROM "
+ TABLE_AUTHORS + " LEFT JOIN " + TABLE_QUOTES + " ON " + AU_WEB_ID
+ " = " + QU_AUTHOR + " GROUP BY " + AU_NAME ;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting Quotes Count
public Integer getQuotesCount() {
String query = "SELECT COUNT(" + QU_TEXT + ") AS count FROM "
+ TABLE_QUOTES;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
Integer count = cursor.getInt(cursor.getColumnIndex("count"));
return count;
}
// ==============================================================================
// Getting Quote ID
public Integer getQotdId() {
String query = "SELECT " + QU_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY RANDOM() LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
Integer id = cursor.getInt(cursor.getColumnIndex(QU_ID));
return id;
}
// ==============================================================================
public void updateSetting(String field, String value) {
open();
ContentValues values = new ContentValues();
values.put(field, value);
// Update Row
database.update(TABLE_SETTINGS, values, null, null);
}
// ==============================================================================
public Cursor getSettings() {
open();
String query = "SELECT * FROM " + TABLE_SETTINGS;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
public int getLastAuthor() {
String query = "SELECT " + AU_WEB_ID + " FROM " + TABLE_AUTHORS
+ " ORDER BY " + AU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex(AU_WEB_ID));
}
// ==============================================================================
public int getLastQuote() {
String query = "SELECT " + QU_WEB_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY " + QU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex(QU_WEB_ID));
}
// ==============================================================================
public void addAuthor(String au_name, String au_picture, int au_web_id) {
open();
ContentValues v = new ContentValues();
v.put(AU_NAME, au_name);
v.put(AU_PICTURE, au_picture);
v.put(AU_PICTURE_SDCARD, 1);
v.put(AU_WEB_ID, au_web_id);
database.insert(TABLE_AUTHORS, null, v);
}
// ==============================================================================
public void addQuote(String qu_text, int qu_author, int qu_web_id) {
open();
ContentValues v = new ContentValues();
v.put(QU_TEXT, qu_text);
v.put(QU_AUTHOR, qu_author);
v.put(QU_FAVORITE, "0");
v.put(QU_WEB_ID, qu_web_id);
database.insert(TABLE_QUOTES, null, v);
}
// ==============================================================================
public void open() throws SQLException {
// database = dbHandler.getReadableDatabase();
database = dbHandler.getWritableDatabase();
}
// ==============================================================================
public void closeDatabase() {
dbHandler.close();
}
Now if I want to update application with more quotes, which changes should I make so that the new and old users don't face any issue ?
I know That Database Version Should Increased, I will it, but What should I put in onUpgrade method ?
I am not expert Android developer, so Please explain me little more if possible, I will very thankful for it.
Thanks
Thanks
Well the Java doc pretty much explains what needs to be done.
From Java doc
Called when the database needs to be upgraded. The implementation
should use this method to drop tables, add tables, or do anything else it
needs to upgrade to the new schema version.
What we do is , alter the tables whenever we have changed the table schema.
In addition you can also perform some data migration if required. Basically its a hook which you got and you can perform any kind of compatibility logic.
cheers,
Saurav

How to fix IndexOutOfBoundsException : invalid index 0 size is 0

I am storing the response of yes|no|maybe into the userrelation table.
For that, I created a table in DBCONTRACT and get the values in a db helper Class.
when I get the values and store into another variable, it throws this error
This the SQL query for the userRelation table
public static abstract class RingeeUserRelationTable implements BaseColumns {
public static final String TABLE_NAME = "user_relation";
public static final String COL1_EVENT_USER_ID = "EVENT_USER_ID";
public static final String COL2_EVENT_ID = "EVENT_ID";
public static final String COL3_RINGEE_USER_ID = "RINGEE_USER_ID";
public static final String COL4_IS_ATTENDING = "IS_ATTENDING";
public static final String COL5_IS_DELETE = "IS_DELETE";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + _ID + " INTEGER PRIMARY KEY," + COL1_EVENT_USER_ID + INTEGER_TYPE + COMMA_SEP + COL2_EVENT_ID + INTEGER_TYPE
+ COMMA_SEP + COL3_RINGEE_USER_ID + INTEGER_TYPE + COMMA_SEP + COL4_IS_ATTENDING + INTEGER_TYPE + COMMA_SEP + COL5_IS_DELETE + INTEGER_TYPE + ")";
public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
public static final String RETRIVE_ALL_USER_DATA = "SELECT " + COL1_EVENT_USER_ID + COMMA_SEP + COL2_EVENT_ID + COMMA_SEP + COL3_RINGEE_USER_ID + COMMA_SEP + COL4_IS_ATTENDING + COMMA_SEP
+ COL5_IS_DELETE + " FROM " + TABLE_NAME;
}
This is the code for getting the value and set to userMOS list
public ArrayList<UserMO> getAllUserRelation() {
ArrayList<UserMO> userMOs = new ArrayList<UserMO>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(DatabaseContract.RingeeUserRelationTable.RETRIVE_ALL_USER_DATA, null );
if (cursor.moveToFirst()) {
do {
UserMO userMO = new UserMO();
userMO.setEventUserId(cursor.getLong(1));
userMO.setEventId(cursor.getLong(2));
userMO.setRingeeUserId(cursor.getLong(3));
userMO.setIsAttending(cursor.getInt(4));
userMO.setIsDelete(cursor.getInt(5));
userMOs.add(userMO);
} while (cursor.moveToNext());
cursor.close();
}
return userMOs;
}
This is the code for getting the isattending value in the Fragment
context = getActivity().getApplicationContext();
dbHelper = new DatabaseHelper(context);
userMOs = dbHelper.getAllUserRelation();
// I got the error here there is no value in a table but in back end the values are stored
int isAttending = userMOs.get(position).getIsAttending();
I am using this isattending for setting the colour of the yes|no|maybe Button
switch(isAttending)
{
case 1:
yesBtn.setBackgroundColor(Color.YELLOW);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.BLUE);
break;
case 2:
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.YELLOW);
break;
case 0:
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.YELLOW);
maybeBtn.setBackgroundColor(Color.BLUE);
break;
}
When I run this project, I get an error: IndexOutOfBoundsException.
Please tell me what is the cause of the error and how to solve this issue
Indexes are 0 based.
Therefore, you need to rewrite your code like so:
public ArrayList<UserMO> getAllUserRelation() {
ArrayList<UserMO> userMOs = new ArrayList<UserMO>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(DatabaseContract.RingeeUserRelationTable.RETRIVE_ALL_USER_DATA, null );
if (cursor.moveToFirst()) {
do {
UserMO userMO = new UserMO();
userMO.setEventUserId(cursor.getLong(0));
userMO.setEventId(cursor.getLong(1));
userMO.setRingeeUserId(cursor.getLong(2));
userMO.setIsAttending(cursor.getInt(3));
userMO.setIsDelete(cursor.getInt(4));
userMOs.add(userMO);
} while (cursor.moveToNext());
cursor.close();
}
return userMOs;
}
Write the following code as shown below:-
public ArrayList<UserMO> getAllUserRelation() {
ArrayList<UserMO> userMOs = new ArrayList<UserMO>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(DatabaseContract.RingeeUserRelationTable.RETRIVE_ALL_USER_DATA, null );
if (cursor.moveToFirst()) {
do {
UserMO userMO = new UserMO();
userMO.setEventUserId(cursor.getLong(1));
userMO.setEventId(cursor.getLong(2));
userMO.setRingeeUserId(cursor.getLong(3));
userMO.setIsAttending(cursor.getInt(4));
userMO.setIsDelete(cursor.getInt(5));
userMos.add(userMO);
} while (cursor.moveToNext());
cursor.close();
}
return userMOs;
}
Its giving you a Array Index out of bound exception as you have not assign anything to your array list. which I had did by adding this line in your code above.
userMos.add(userMo);

Android: How to change value of sqlite column

I am relatively new to using sqlite in the android world and I currently I my sqlite database set up like the following:
db.execSQL("CREATE TABLES " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_LOCKERNUMBER
+ " TEXT NOT NULL, " + KEY_STATUS + " INTEGER DEFAULT 0, "
+ KEY_PIN + " INTEGER DEFAULT 0);");
And I have the following methods to insert data into the database:
// function to add lockers to database
public long createLockerEntry(String lockerNumber, int status) {
ContentValues cv = new ContentValues();
cv.put(KEY_LOCKERNUMBER, lockerNumber);
cv.put(KEY_STATUS, status);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
// function to create a pin for the locker
public void createPin(String lockerNumber, int pin, int status) {
}
// function to remove pin
public void removePin(String lockerNumber, int pin, int status) {
}
My intentions are to add a pin number for a certain locker number to the KEY_PIN column within the method Create pin and then change the status value to 1. I would assume I would use the where clause statement but I am not completely sure about the syntax or if that is the write approach. Any suggestions?
The method you want is update()
You can read about it by searching for "update" on this page:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
One way to use this would be:
// function to create a pin for the locker
public void createPin(tring lockerNumber, int pin, int status) {
ContentValues cv = new ContentValues()
cv.put(KEY_PIN, pin);
cv.put(KEY_STATUS, status);
ourDatabase.update(DATABASE_TABLE, cv, KEY_LOCKERNUMBER + " = ?"
, new String[] {lockerNumber});
}
Here's an example where I toggle the value of an entry. It is an int value used as binary (i.e. 1 or 0).
The two methods checkAsWildTest, and uncheckAsWildTest.
public void checkAsWildTest(Cursor c, int val) {
assertDbOpen();
String[] _params = { String.valueOf(c.getInt(ID_COLUMN)) };
//next 4 lines are just for debug
log(".uncheckAsWildTest(), " + "c.getCount() = " + c.getCount());
log("row selected = " + c.getInt(ID_COLUMN));
log("cursor content: " + c.getString(ANSWERS_RESPONSE_COLUMN));
log("cursor columns" + Arrays.toString(c.getColumnNames()));
ContentValues cv = new ContentValues();
cv.put(KEY_ANSWERS_CHECKED, val);
db.update(ANSWERS_TABLE, cv, "_id=?", _params);
}
public void uncheckAsWildTest(Cursor c) {
assertDbOpen();
int unchecked = 0;
String[] _params = { String.valueOf(c.getInt(ID_COLUMN)) };
//next 4 lines are just for debug
log(".uncheckAsWildTest(), " + "c.getCount() = " + c.getCount());
log("column selected = " + c.getInt(ID_COLUMN));
log("cursor content: " + c.getString(ANSWERS_RESPONSE_COLUMN));
log("cursor columns" + Arrays.toString(c.getColumnNames()));
ContentValues cv = new ContentValues();
cv.put(KEY_ANSWERS_CHECKED, unchecked);
db.update(ANSWERS_TABLE, cv, "_id=?", _params);
}
I believe you can work with this, and modify it for your purposes.

Categories