cursor count is 1 whereas the table has 3 rows - android-sqlite

I m trying to populate sql table and then retrieve data from it. Following is my code.
public void addQuestion(Question quest)
{
int id = 1;
ContentValues values = new ContentValues();
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST1);
onCreate(db);
values.put(KEY_QUES, quest.getQuestion());
values.put(KEY_ANSWER, quest.getAnswer());
values.put(KEY_OPTA, quest.getOptA());
values.put(KEY_OPTB, quest.getOptB());
values.put(KEY_OPTC, quest.getOptC());
db.insert(TABLE_QUEST1, null, values);
System.out.println("Added in database: " + quest.getQuestion());
}
public ArrayList<Question> getAllQuestions() {
System.out.println("getting rows 1");
ArrayList<Question> quesList = new ArrayList<Question>();
System.out.println("getting rows 2");
Cursor cursor = null;
SQLiteDatabase db = getReadableDatabase();
System.out.println("getting rows ");
cursor = db.rawQuery("SELECT * FROM " + TABLE_QUEST1, null);
if (!cursor.moveToFirst()) {
System.out.println("No data in the database ");
} else {
System.out.println("theres data in the database ");
quesList = new ArrayList<Question>();
do {
System.out.print("total rows " + cursor.getCount());
Question quest = new Question();
quest.setID(cursor.getInt(0));
quest.setQuestion(cursor.getString(1));
quest.setAnswer(cursor.getString(2));
quest.setOptA(cursor.getString(3));
quest.setOptB(cursor.getString(4));
quest.setOptC(cursor.getString(5));
quesList.add(quest);
} while (cursor.moveToNext());
cursor.close();
}
}
I have 4 rows of data in my table and I can see that with the print statement "added in database"
but when i actually read it the cursor just reads row 1 and moves out of the while loop. what could potentially be wrong.
tia

Your code was absolutely fine except placing drop command in the loop. As mentioned in the earlier comments, please make sure to avoid calling drop query each time and you'll find the result.

As Santosh has pointed out DROPPING the table (as per db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST1);) and then re-creating it (as per onCreate(db);) will delete the table and then re-create the table removing any rows/data that had previously been added to the table.
As such it's simply a matter of removing those two lines of code, Also there appears to be no need for the line int id = 1;, so perhaps remove this, as per :-
public void addQuestion(Question quest)
{
ContentValues values = new ContentValues();
SQLiteDatabase db = this.getWritableDatabase();
values.put(KEY_QUES, quest.getQuestion());
values.put(KEY_ANSWER, quest.getAnswer());
values.put(KEY_OPTA, quest.getOptA());
values.put(KEY_OPTB, quest.getOptB());
values.put(KEY_OPTC, quest.getOptC());
db.insert(TABLE_QUEST1, null, values);
System.out.println("Added in database: " + quest.getQuestion());
}
P.S. you may consider not using hard coded column offsets but instead obtain offsets according to column names by utilising the getColumnIndex(column_name) Cursor method. e.g. :-
Question quest = new Question();
quest.setID(cursor.getInt(cursor.getColumnIndex("name_of_your_id_columm")));
quest.setQuestion(cursor.getString(cursor.getColumnIndex(KEY_QUES)));
quest.setAnswer(cursor.getString(cursor.getColumnIndex(KEY_ANSWER)));
quest.setOptA(cursor.getString(cursor.getColumnIndex(KEY_OPTA)));
quest.setOptB(cursor.getString(cursor.getColumnIndex(KEY_OPTB)));
quest.setOptC(cursor.getString(cursor.getColumnIndex(KEY_OPTC)));
quesList.add(quest);
Noting that instead of "name_of_your_id_columm", you may have something like KEY_ID defined, if so use that, thus you have a single definition so it reduces the chance of inadvertently mispelling column names or miscalculating the offsets.

Related

Android SQLite not returning data for given search term

I am trying to build a search interface but the SQLite database returns nothing here is the code for search function
public List<DiaryModel> searchData(String srchTerm){
List<DiaryModel> data2=new ArrayList<>();
SQLiteDatabase db1 = this.getWritableDatabase();
String sql="SELECT * FROM "+DB_TABLE+" WHERE "+KEY_HEADING+" LIKE '"+srchTerm+"%'";
Cursor cursor2 =db1.rawQuery(sql,null);
cursor2.moveToFirst();
StringBuilder stringBuffer2;
stringBuffer2 = new StringBuilder();
DiaryModel diaryModel2;
while (cursor2.moveToNext()){
diaryModel2 = new DiaryModel();
String heading = cursor2.getString(cursor2.getColumnIndexOrThrow("heading"));
String desc = cursor2.getString(cursor2.getColumnIndexOrThrow("desc_"));
diaryModel2.setHeading(heading);
diaryModel2.setDesc(desc);
stringBuffer2.append(diaryModel2);
data2.add(diaryModel2);
}
return data2;
}
but when I print everything the Database returns data, here is the code for get Data used for printing data present in Database
public List<DiaryModel> getdata(){
List<DiaryModel> data=new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor =db.rawQuery("SELECT * FROM diary_db", null);
cursor.moveToFirst();
StringBuilder stringBuffer = new StringBuilder();
DiaryModel diaryModel;
while (cursor.moveToNext()){
diaryModel = new DiaryModel();
String heading = cursor.getString(cursor.getColumnIndexOrThrow(KEY_HEADING));
String desc = cursor.getString(cursor.getColumnIndexOrThrow(KEY_DESC));
diaryModel.setHeading(heading);
diaryModel.setDesc(desc);
stringBuffer.append(diaryModel);
data.add(diaryModel);
}
return data
}
The thing is only this SQL statement is working
SELECT * FROM diary_db
and if any condition is put nothing returns.
There is something that you are doing wrong in both methods:
cursor.moveToFirst();
and then:
while (cursor.moveToNext()){
.................
}
This way you miss the 1st row of the results, because after you move the cursor to the 1st row, you move once again to the next row.
So delete this:
cursor.moveToFirst();
from both methods.

Query always returns false in Sqlite Android

I want to check the username and password with sqlite table,In my case query always returns false...
This is my Query...
public boolean validateUser(String u_name, String p_word){
Cursor c = getReadableDatabase().rawQuery(
"SELECT FNAME,PASSWORD FROM " + TABLE_NAME + " WHERE "
+ fname + "='" + u_name+"'AND "+ password +"='"+ p_word+"'" , null);
if (c!=null)
{
return true;
}
else{
return false;
}
}
Checking whether or not the Cursor is null is basically useless as a valid Cursor will be returned by rawQuery. That is no data to extract will result in an empty Cursor with no rows, whilst if data has been extracted the Cursor will have 1 or more rows.
You should check whether or not the Cursor is empty by using the Cursor getCount() method which will return 0 if there are no rows or the number of rows. Alternately you could use some of the Cursor's move methods which will return true/false depending upon whether the move can be performed. e.g if (c.moveToFirst) { ... //row(s) exist} else { ... //no rows exists }.
You should also close the Cursor before returning. So perhaps use :-
public boolean validateUser(String u_name, String p_word){
Cursor c = getReadableDatabase().rawQuery(
"SELECT FNAME,PASSWORD FROM " + TABLE_NAME + " WHERE "
+ fname + "='" + u_name+"'AND "+ password +"='"+ p_word+"'" , null);
int count = c.getCount(); // get the number of rows
c.close(); // Close the Cursor
return count > 0; // return result (no data found = false, else true)
Many would recommend not using rawQuery but rather the convenience Cursor query method. This could be :-
public boolean validateUser(String u_name, String p_word) {
String[] columns = new String[]{
FNAME,
PASSWORD
};
String whereclause = FNAME + "=? AND " + PASSWORD + "=?";
String[] whereargs = new String[]{
u_name,
p_word
};
Cursor c = this.getWritableDatabase().query(
TABLE_NAME,
columns,
whereclause,
whereargs,
null,null,null
);
int count = c.getCount();
c.close();
return count > 0;
}
Note the above code is in-principle code and hasn't been tested so it may contain typing errors.
The above code assumes that the method is within the Database Helper class (i.e. a subclass of SQLiteOpenHelper).
The assumption has been made that FNAME and PASSWORD are the correct String variables to be used for the column names as opposed to fname and password
Assumptions have been made due to the limited code made available.

Select query on postgresql database result is empty. Am I using wrong logic?

I am using Npgsql for postgresql in C++/CLI. So, the problem is, I have a db on my computer, and I am trying to select some of data from it's "movies" table. I already entered some data inside it, so I know that it has some data. But when I try to select some of them, answer to my query is empty. My code is like below:
public: string* SelectData(string* torrent)
{
conn->Open();
String ^ query = "SELECT title, director, actors, genre FROM movies";
Npgsql::NpgsqlCommand ^ command = gcnew NpgsqlCommand(query, conn);
try{
Npgsql::NpgsqlDataReader ^ dr = command->ExecuteReader();
for (int i = 0; i < N_TORRENT; i++)
{
if(dr->Read())
{
string std1 = toStandardString((String^)dr[0]);
string std2 = toStandardString((String^)dr[1]);
string std3 = toStandardString((String^)dr[2]);
string std4 = toStandardString((String^)dr[3]);
torrent[i] = std1 + " " + std2 + " " + std3 + " " + std4;
}
}
return torrent;
}
finally{
conn->Close();
}
}
(For the ones who will look for this question's answer)
Problem solved when I changed my query and look for the "title" column that are not empty. But this is ridiculus, so I beleive the problem was about pgAdmin. Because my insert query was not working either, but I added "rowseffected" variable and it shows the effected row's number and looks like it is working. So the problem is probably about the pgAdmin.

get primary key of last inserted record with JPA

I've been using JPA to insert entities into a database but I've run up against a problem where I need to do an insert and get the primary key of the record last inserted.
Using PostgreSQL I would use an INSERT RETURNING statement which would return the record id, but with an entity manager doing all this, the only way I know is to use SELECT CURRVAL.
So the problem becomes, I have several data sources sending data into a message driven bean (usually 10-100 messages at once from each source) via OpenMQ and inside this MDB I persists this to PostgreSQL via the entity manager. It's at this point I think there will be a "race condition like" effect of having so many inserts that I won't necessarily get the last record id using SELECT CURRVAL.
My MDB persists 3 entity beans via an entity manager like below.
Any help on how to better do this much appreciated.
public void onMessage(Message msg) {
Integer agPK = 0;
Integer scanPK = 0;
Integer lookPK = 0;
Iterator iter = null;
List<Ag> agKeys = null;
List<Scan> scanKeys = null;
try {
iag = (IAgBean) (new InitialContext()).lookup(
"java:comp/env/ejb/AgBean");
TextMessage tmsg = (TextMessage) msg;
// insert this into table only if doesn't exists
Ag ag = new Ag(msg.getStringProperty("name"));
agKeys = (List) (iag.getPKs(ag));
iter = agKeys.iterator();
if (iter.hasNext()) {
agPK = ((Ag) iter.next()).getId();
}
else {
// no PK found so not in dbase, insert new
iag.addAg(ag);
agKeys = (List) (iag.getPKs(ag));
iter = agKeys.iterator();
if (iter.hasNext()) {
agPK = ((Ag) iter.next()).getId();
}
}
// insert this into table always
iscan = (IScanBean) (new InitialContext()).lookup(
"java:comp/env/ejb/ScanBean");
Scan scan = new Scan();
scan.setName(msg.getStringProperty("name"));
scan.setCode(msg.getIntProperty("code"));
iscan.addScan(scan);
scanKeys = (List) iscan.getPKs(scan);
iter = scanKeys.iterator();
if (iter.hasNext()) {
scanPK = ((Scan) iter.next()).getId();
}
// insert into this table the two primary keys above
ilook = (ILookBean) (new InitialContext()).lookup(
"java:comp/env/ejb/LookBean");
Look look = new Look();
if (agPK.intValue() != 0 && scanPK.intValue() != 0) {
look.setAgId(agPK);
look.setScanId(scanPK);
ilook.addLook(look);
}
// ...
The JPA spec requires that after persist, the entity be populated with a valid ID if an ID generation strategy is being used. You don't have to do anything.

Using Drag-Sort ListView with SQLite DB

I'm trying to create a simple to-do-list app with an SQLite DB and a Drag-Sort ListView.
Right now I am binding data from an SQLite database cursor into a ListView using a SimpleCursorAdapter and adding items with an EditText view as explained in this tutorial.
I have moved everything into one activity and I have swapped the plain ListView with a Drag-Sort ListView. My issue is connecting the DB and Drag-Sort ListView together. The DLSV demos use a predefined array to fill fill the DSLV.
Snippet form DSLV:
DragSortListView lv = (DragSortListView) getListView();
lv.setDropListener(onDrop);
lv.setRemoveListener(onRemove);
array = getResources().getStringArray(R.array.jazz_artist_names);
list = new ArrayList<String>(Arrays.asList(array));
adapter = new ArrayAdapter<String>(this, R.layout.list_item1, R.id.text1, list);
setListAdapter(adapter);
Snippet from my existing code:
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
...
mDbHelper.createNote(noteName, "");
fillData();
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = mDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
int[] to = new int[] { R.id.text1 };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);
}
Thank you and sorry if this doesn't make all that much sense.
Since you cannot reorder the items in a Cursor, you have to create a mapping between Cursor positions and ListView positions. This is done for you by the DragSortCursorAdapter class and subclasses so that the drag and drop reordering is maintained visually. If you need the new orders persisted (like to your database), then you must implement that logic yourself. The method getCursorPositions() will help you with this.
I have made use of Drag sort list view. Its amazing! but instead of using the dragsortcursoradapter i created my own trick. here it is.
What i have done is that whenever i swapped any item, i passed the new swapped list in an array to the database, deleted the table and recreated the new updated table. here is my code
here is the code snippet from my database handler
public void onUpdateToDoTable(ArrayList<Task> taskList) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKTODO);
String CREATE_TASK_TODO_TABLE = "CREATE TABLE IF NOT EXISTS "
+ TABLE_TASKTODO + "(" + SEQ_ID + " INTEGER PRIMARY KEY,"
+ TASK_NAME + " TEXT )";
db.execSQL(CREATE_TASK_TODO_TABLE);
for (int i = 0; i < taskList.size(); i++) {
ContentValues values = new ContentValues();
values.put(TASK_NAME, taskList.get(i).getTask());
db.insert(TABLE_TASKTODO, null, values);
}
db.close();
}
then on using drop listener
i called the above method..
private DragSortListView.DropListener onDrop = new DragSortListView.DropListener() {
#Override
public void drop(int from, int to) {
Task item = adapter.getItem(from);
adapter.notifyDataSetChanged();
adapter.remove(item);
adapter.insert(item, to);
db.onUpdateToDoTable(list);
Log.d("LIST", db.getAllToDoTasks().toString());
}
};
db is my object of database handler. whole source code is available at dragdroplistview. amazing example. this was a life saver for me. Ciao!
There is a github project available at https://github.com/jmmcreynolds/dslv-db-demo
This demo includes a working example of how to setup a DragSortListView that will save the changes that you make to the list (position, add/delete) to a database.
I have used it just now. Its perfect demo project available for using DSLV with SQLiteDB.
Thanks to github user jmmcreynolds.