ContentValues does not insert values into table - java

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?!

Related

How to get row cursor with primary key android

I have a table with the following
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL( "CREATE TABLE " + TABLE_NAME + " (" + "ID" + " INTEGER PRIMARY KEY," +
COLUMN_TOPIC + " TEXT," + COLUMN_LOCATION + " TEXT)");
}
I am trying to get all the data at a given rowid
public void getRowCursor(int position){
SQLiteDatabase database = getWritableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " +
"ID" + "=" + String.valueOf(position), null);
cursor.moveToFirst();
cursor.close
//or
Cursor cursor = database.query(TABLE_NAME, null, "ID", new String[]{
String.valueOf(position)}, null, null, null, null );
cursor.moveToFirst();
cursor.close
database.close
}
I get an error
java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
I did populate the table. How do I return a cursor based on the position of entry.
How do I return a cursor based on the position of entry
First, your method getRowCursor() should return a Cursor.
Also, you should not close the returned cursor because I assume that you want to use its results somehow.
Your code with the method rawQuery() should work like this:
public Cursor getRowCursor(int position) {
SQLiteDatabase database = getWritableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " WHERE ID = " + String.valueOf(position);
Cursor cursor = database.rawQuery(sql, null);
// cursor.moveToFirst();
return cursor;
}
But, the safe and recommended way to pass parameters to a query is with ? placeholders instead of concatenating them inside the sql statement and passing them as array items in the 2nd argument of rawQuery():
public Cursor getRowCursor(int position) {
SQLiteDatabase database = getWritableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " WHERE ID = ?";
Cursor cursor = database.rawQuery(sql, new String[] {String.valueOf(position)});
// cursor.moveToFirst();
return cursor;
}
Note that moveToFirst() moves the cursor's index at the 1st row of the cursor (if it exists).
I commented out this call, because you should use it after you call getRowCursor() like this:
Cursor cursor = getRowCursor(10); // or any other ID
if (cursor.moveToFirst()) { // the cursor contains at least 1 row
....
} else { // the cursor is empty
....
}
and when you are done with the cursor:
cursor.close();

How to update the value of the existing columns in SQLite android ? (not able to do in my project)

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.

How to insert data to existing column where id = ...?

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.

SQL: Can't get count(*) to work - why so?

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;
}

how to fetch data from 2 sqlite tables and insert it into 3rd table in android? i am new to android...i have tried bt it does not work?

table 1 is MsgTable, 2nd is ContactTable & the third 1 is KeyTable...
i have to select data from first 2 tables & insert it into 3rd table??
public void setKeyValues(String msg_id, String contact_id )//insert intokeytable(msgid - contact)
{
db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("Msg_Id", msg_id);
values.put("Contact_Id", contact_id);
i = db.insert("KeyTable", null, values);//contact
if(i != 0)
{
}
}
public ArrayList<String> getValues()
{
ArrayList<String> arr = null;
try
{
db = getReadableDatabase();
arr = new ArrayList<String>();
Cursor c1= null;
Cursor c2 = null;
c1 = db.rawQuery("select Msg_id from KeyTable where Contact_id = 1", null);
while(c1.moveToNext())
{
String msg = c1.getString(c1.getColumnIndex("MSG"));
String str = msg ;
arr.add(str);
Log.d("fuuast",str);
}
c2 = db.rawQuery("select Contact_id from KeyTable where Msg_id = 1", null);
while(c2.moveToNext())
{
String contact = c2.getString(c2.getColumnIndex("Contact"));
String str = contact ;
arr.add(str);
Log.d("fuuast",str);
}
}catch(Exception ex)
{
ex.printStackTrace();
}
return arr;
}
}

Categories

Resources