I created table in my database with scores (10 records). They are now empty but I want them to be updated after user make some quiz.
Now my function looks like this :
public boolean insertScore(float score, int id){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Score", score);
long result = db.insert("Scores" , null, contentValues);
if (result == -1){
return false;
}
else{
return true;
}
}
but I would like to put the data to row with id equals the id argument. How can I do it ?
What you want is to update the existing values of the column score and not insert new rows:
public boolean updateScore(float score, int id){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Score", score);
long result = db.update("Scores", contentValues, "id = ?", new String[] {String.valueOf(id)});
db.close();
return result > 0;
}
The method update() returns the number of the rows affected, so your method updateScore() will return true if the row with specified id was updated.
Related
I am trying to update the existing column of my table but am not able to do so....
There are no errors it is just not getting updated.
My code are there below
Calling the function by passing value a is the _id in which i want to change and i is the value which i want to insert.
boolean isUpdate = mDbHelper.updatedata(String.valueOf(a),String.valueOf(i));
The function which I am using to change the values
public boolean updatedata(String id,String books){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Lib_student.COLUMN_STUDENT_BOOKS,books);
Cursor cursor = db.rawQuery("select * from Library_Student where books=?",new String[]{books});
long r = db.update("Library_Student",contentValues,"books=?",new String[]{books});
if (r == -1){
return false;
}else {
return true;
}
}
Here is the table which i need to edit..
String SQL_CREATE_LIBRARY_TABLE_STUDENT = "CREATE TABLE "+ Lib_student.TABLE_NAME + " ("
+Lib_student._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+Lib_student.COLUMN_STUDENT_NAME+ " TEXT NOT NULL, "
+Lib_student.COLUMN_STUDENT_EMAIL+ " TEXT, "
+Lib_student.COLUMN_STUDENT_AGE+ " INTEGER , "
+Lib_student.COLUMN_STUDENT_GENDER+ " TEXT ,"
+Lib_student.COLUMN_STUDENT_NUMBER+ " INTEGER ,"
+Lib_student.COLUMN_STUDENT_ADDRESS+ " TEXT ,"
+Lib_student.COLUMN_STUDENT_BOOKS + " INTEGER );";
First, there is no need to select the row that you want to update, so remove this line:
Cursor cursor = db.rawQuery("select * from Library_Student where books=?",new String[]{books});
Also, you must pass the id and not the value of books as an argument to the method update():
public boolean updatedata(String id, String books) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Lib_student.COLUMN_STUDENT_BOOKS, books);
return db.update("Library_Student", contentValues, Lib_student._ID + " = ?", new String[]{id}) > 0;
}
The method update() returns the number of the updated rows (it never returns -1), so you must compare that number to 0 and return true if it is greater than 0 or false if it is 0.
I'm trying to query a database for the count of entries that match the given ID, but I can't come up with a working solution.
There are two of each type of account that correspond to the userID of 1, for some reason the first method outputs "1" and the second "0". I can show the mainactivity and the database shchema if needed as well.
public int numberOfDebitAccounts(int userID){
int numOf_accs = 0;
String query = "select count(*) from debitAccount where userID = '" +userID+"'";
openDatabase();
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()) {
numOf_accs = cursor.getInt(0);
System.out.println("Number of debit accs: " + numOf_accs);
}
cursor.close();
closeDatabase();
return numOf_accs;
}
public int numberOfCreditAccounts(int userID){
int numOf_accs = 0;
String query = "select count(accountID) from creditAccount where userID = '" +userID+"'";
openDatabase();
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()) {
numOf_accs = cursor.getInt(0);
System.out.println("number of credit accounts: " + numOf_accs);
}
closeDatabase();
return numOf_accs;
}
I am trying to make search history through SQLite in Android Studio.
When I try to get information from SQLite DB using getCount(),
it keeps returning 0.
I have checked if there are any data in DB by terminal.
However it showed results that there are data.
Please help me.
public String[][] getResult(){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM AlYak_History", null);
Log.d("getCount", valueOf(cursor.getCount()));
String[][] result = new String[cursor.getCount()][];
cursor.moveToFirst();
while(cursor.moveToNext()){
for(int i = 0 ; i < 12 ; i ++){
result[cursor.getPosition()][i] = cursor.getString(i+1);
}
}
cursor.close();
db.close();
return result;
}
Are you sure you connect to the DB? Your constructor should be like this:
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
It should be String.valueOf() not valueOf
This one work for me
public int getResultCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
I have this:
public void addNewNote(Note n) {
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE, n.getNote_title());
values.put(COLUMN_TEXT, n.getNote_text());
values.put(COLUMN_FK, n.getNote_ForeignKey()); //this column is integer type
values.put(COLUMN_PT, String.valueOf(n.getNote_PersonType())); //this column is char type
SQLiteDatabase db = this.getWritableDatabase();
db.insert("tbl_Notes",null, values);
}
as my add method, as I traced it, the record is added successfully. but when I try to get my note with below code, findNote always returns null and cnt is always 0.
public Note findNote(int note_id){
String query = "select * from tbl_Notes"; // where " + COLUMN_ID + " = " + note_id;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
int cnt = cursor.getCount();
Note N = new Note();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
N.setNote_title(cursor.getString(1)); //title column
N.setNote_text(cursor.getString(2)); //text body column
N.setNote_ForeignKey(Integer.parseInt(cursor.getString(3))); //foreign key column
N.setNote_PersonType(cursor.getString(4).charAt(0)); //person type column
cursor.close();
}else {
N = null;
}
return N;
}
and here is my onClick which fires addNewNote:
Note myNote = new Note(
txt_Title.getText().toString(),
foreignKey,
personType,
txt_Body.getText().toString()
);
tbl_notes.addNewNote(myNote);
what am I doing wrong?!
I am working on an app which contains an Android SQLite database. I add and delete rows in this database. When I delete my row, it is based on the ROWID. But I found out, that despite I delete the row, the ROWID remains. So for example if I have 3 rows in my database and delete the 2nd row, my third row will not change to 2 it remains 3. Then if I add a row, it will be 4.
So my question is, how to do that when I delete a row, and add a new one then the number of the added row would equal to the deleted row. So for example if I delete the first row, than the database will show me next to the other rows 1,2,3... and not 2,3,4...
Sorry, maybe it is a little bit complicated, but I hope it makes sense.
Here is my code:
public HotOrNot open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String name, String hotness) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_HOTNESS, hotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iHotness = c.getColumnIndex(KEY_HOTNESS);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iHotness) + "\n";
}
return result;
}
public String getName(long l) throws SQLException{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String name = c.getString(1);
return name;
}
return null;
}
public String getHotness(long l) throws SQLException{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String hotness = c.getString(2);
return hotness;
}
return null;
}
public void updateEntry(long lRow, String mName, String mHotness) throws SQLException{
// TODO Auto-generated method stub
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_NAME, mName);
cvUpdate.put(KEY_HOTNESS, mHotness);
ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID + "=" + lRow, null);
}
public void deleteEntry(long lRow1) throws SQLException{
// TODO Auto-generated method stub
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + lRow1, null);
}
}
I know that it can't be done using ROWID, because it is unique for each row.
Could you please write the code how to solve this problem, because I am beginner in Android and also in SQLite.
Thanks in advance
SQLite keeps track of the largest ROWID that a table has ever held
using the special SQLITE_SEQUENCE table.
You can update SQLITE_SEQUENCE table-
UPDATE SQLITE_SEQUENCE SET seq = <n> WHERE name = <table_name>
n is the rowid - 1
Similar question.