So here it goes, i have this application retrieves records from database, i have 5 entries from my database, and retrieved its using this code;
Cursor c = dbconnection.rawQuery("SELECT * from Patients", null);
after that i looped it to retrieve the data pero row in my Database as such;
c.moveToFirst();
while(!c.isAfterLast())
{
//Some code to put records per column in to a Patient Object
c.moveToNext();
}
So my problem is that as it enters the loop my Emulator freezes and as i tried to display per record into a Log, i won't cuz the emulator it self already frozed.
Can somebody enlighten me into this matter, This issue is really really new to me
EDIT
yes already tried what baya and ofir suggested.. they worked out but i have this null error during iteration with this loop code
Cursor c = dbHelper.retrieveAllData();
c.moveToFirst();
while(c.moveToNext())
{
Log.d("dbcheck",Integer.toString(c.getPosition()));
//Log.d("dbcheck",c.getString(c.getColumnIndex("firstname")));
//Log.d("dbcheck",c.getString(c.getColumnIndex("lastname")));
**p.setFname(c.getString(c.getColumnIndex("firstname")));**
p.setMi(c.getString(c.getColumnIndex("middleinitial")));
p.setLname(c.getString(c.getColumnIndex("lastname")));
p.setAddr(c.getString(c.getColumnIndex("address")));
p.setAge(c.getInt(c.getColumnIndex("age")));
p.setMed_history(c.getString(c.getColumnIndex("med_history")));
p.setPat_status(c.getString(c.getColumnIndex("status")));
patientList.add(p);
}
i have a null exception error on the p.setFname() line.. i don't know how it became null where in fact i already displayed it with Log using that code that is commented out..
Just try,
Cursor c = dbconnection.rawQuery("SELECT * from Patients", null);
if (c.getCount() > 0) {
Patient p;
while(c.moveToNext) {
//initialize ur object to store new patient info.
p = new Patient();
p.setFname(c.getString(c.getColumnIndex("firstname")));
//add newly created patient to ur list
patientList.add(p);
}
}
c.close();
Try do it like this:
// return all columns
Cursor cursor = mDb.query(Patients, null, null, null, null, null, null);
if ((cursor != null) && (cursor.getCount() > 0)) {
while(cursor.moveToNext()){
//Some code to put records per column in to a Patient Object
}
cursor.close();
}
Related
This question already has answers here:
What is a stack trace, and how can I use it to debug my application errors?
(7 answers)
Closed 5 years ago.
My dbhelper.java have method
public Cursor report(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM Employees", null);
return c;
}
Mainactivity.java
private List<Front1> viewReport(){
List<Front1> employeeList1 = new ArrayList<>();
Cursor c = db.report();
if (c != null && c.getCount() > 0) { // Add the addition condition
if (c.moveToFirst()) {
do{
String ids=c.getString(c.getColumnIndex("e_ids"));
String name=c.getString(c.getColumnIndex("e_name"));
Front1 front1=new Front1(ids,name1);
employeeList1.add(front1);
}while (c.moveToNext());}
}else{
Front1 front1=new Front1("101","suran");
employeeList1.add(front1);
}
I have employee table.first time application install my table has empty so application crash.if i add dumny data stop application crash but user delete dummy data again application crash.how to solve null object reference initial stage .it mean select statement used if resultset empty .i want my application run not crash.any guidence will helpfull to me.
As Cursor doesn't return null if the table is empty, you should use getCount() function to solve your problem. Your code should look like below:
if (c != null && c.getCount() > 0) { // Add the addition condition
if (c.moveToFirst()) {
do{
String ids=c.getString(c.getColumnIndex("e_ids"));
String name=c.getString(c.getColumnIndex("e_name"));
Front1 front1=new Front1(ids,name1);
employeeList1.add(front1);
}while (c.moveToNext());}
}
Your issue is that a null Cursor will not be returned from a query. Rather in the situation of no data being extracted the Cursor will be empty.
This could be checked using the Cursor getCount() method. However, it is just as easily be checked by checking the return value (true or false) of a move???? method such as moveToNext. MoveToNext can also be used to traverse numerous rows in a while loop. As such, perhaps the simplest solution is to use :-
if (c.moveToNext()) {
String ids=c.getString(c.getColumnIndex("e_ids"));
String name=c.getString(c.getColumnIndex("e_name"));
Front1 front1=new Front1(ids,name1);
employeeList1.add(front1);
}
Obviously you may need to check the size of the returned List, as it's size could be 0.
I am using custom adapter extending cursor adapter for displaying data in listview, to display particular phone number i have passed the id to a method in database class but it is showing
errorandroid.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
while placing debugger in the the method it is not going after the line
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
Can any one help me to solve it.
This is the code:
public String getNumberFromId(int id)
{
String num;
db= this.getReadableDatabase();
Cursor cursor = db.query(scheduletable, new String[] { "ContactNumber" },"_id="+id, null, null, null, null);
cursor.moveToFirst();
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
cursor.close();
db.close();
return num;
}
Whenever you are dealing with Cursors, ALWAYS check for null and check for moveToFirst() without fail.
if( cursor != null && cursor.moveToFirst() ){
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
cursor.close();
}
Place logs appropriately to see whether it is returning null or an empty cursor. According to that check your query.
Update Put both the checks in a single statement as mentioned by Jon in the comment below.
Update 2 Put the close() call within the valid cursor scope.
try this.. this will avoid an Exception being thrown when the cursor is empty..
if(cursor != null && cursor.moveToFirst()){
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
cursor.close();
}
First check this Condition before fetching data
if(cursor!=null && cursor.getCount()>0){
cursor.moveToFirst();
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
}
Check the return value from moveToFirst(), before you try to read anything from the cursor. It looks as if no results are being returned.
a save schema to query Cursors is
// just one
Cursor cursor = db.query(...);
if (cursor != null) {
if (cursor.moveToFirst()) {
value = cursor.getSomething();
}
cursor.close();
}
// multiple columns
Cursor cursor = db.query(...);
if (cursor != null) {
while (cursor.moveToNext()) {
values.add(cursor.getSomething());
}
cursor.close();
}
In case people are still looking:
Instead of searching for "ContactNumber" try searching for Phone.NUMBER. The tutorial has the code with more details: http://developer.android.com/training/basics/intents/result.html
try to uninstall the app and then again test it... actually the sqlite db is created only once when the app is first install... so if you think your logic is current then reinstalling the app will do the trick for you. !!!!
My query return 198 registers but cursor only read one register.
Why?
The mCount property of Cursor show 198.
This code:
public ArrayList<EnderecoOficina> retornarListaEnderecoOficina(String sCampo,
String sWhere) {
ArrayList<EnderecoOficina> lista = new ArrayList<EnderecoOficina>();
String query = String.format("SELECT %s FROM %s WHERE %s",
sCampo,
MyDBConstants.TABLE_OFICINAS,
sWhere);
SQLiteDatabase db = dbHandler.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
int i = 0;
if (cursor != null && cursor.moveToFirst()){
EnderecoOficina item = new EnderecoOficina(i++,
cursor.getString(0),
cursor.getString(1),
cursor.getString(2));
lista.add(item);
} while (cursor.moveToNext());
cursor.close();
db.close();
return lista;
}
image link (my points not allow attach image here).
I think you're confusing while syntax.
while (cursor.moveToNext());
Will loop without doing anything until the Cursor is empty. I think you wanted a do/while as explained by CommonsWare answer.
In my opinion, this is an unnecessary complicated way to do it. A lot of people don't know how to use Android Cursor. I've seen all kinds of complicated ways to do it (checking for null, moving to first, moving to index...), but this is the simplest way:
try {
// Loop while there are records on the Cursor
while (cursor.moveToNext()) {
EnderecoOficina item = new EnderecoOficina(i++,
cursor.getString(0),
cursor.getString(1),
cursor.getString(2));
lista.add(item);
}
} finally {
// Make sure the cursor is closed no matter what
cursor.close();
}
There's no need to check for null, Android Cursor API never returns a null cursor. You also need to close the Cursor once you've finished with it.
I am a programming newbie
and I found this piece of code in the internet and it works fine
Cursor c=db.query(DataBase.TB_NAME, new String[] {DataBase.KEY_ROWID,DataBase.KEY_RATE}, DataBase.KEY_ROWID+"= 1", null, null, null, null);
if(c!=null)
{
c.moveToFirst();
}
but I am not able to understand the use of the
if(c!=null)
{
c.moveToFirst();
}
part. What does it do exactly , and if I remove the
if(c!=null) { c.moveToFirst(); }
part, the code doesn't work.
The docs for SQLiteDatabase.query() say that the query methods return:
"A Cursor object, which is positioned before the first entry."
Calling moveToFirst() does two things: it allows you to test whether the query returned an empty set (by testing the return value) and it moves the cursor to the first result (when the set is not empty). Note that to guard against an empty return set, the code you posted should be testing the return value (which it is not doing).
Unlike the call to moveToFirst(), the test for if(c!=null) is useless; query() will either return a Cursor object or it will throw an exception. It will never return null.
if (c.moveToFirst()) {
while(!c.isAfterLast()) { // If you use c.moveToNext() here, you will bypass the first row, which is WRONG
...
c.moveToNext();
}
}
Cursor is not a Row of the result of query. Cursor is an object that can iterate on the result rows of your query. Cursor can moves to each row. .moveToFirst() method move it to the first row of result table.
moveToFirst() method moves the cursor to the first row. It allows to perform a test whether the query returned an empty set or not. Here is a sample of its implementation,
if (cursor.getCount() == 0 || !cursor.moveToFirst()) {
return cursor.getLong(cursor.getColumnIndexOrThrow(ID_COLUMN));
cursor.close();
what macio.Jun says is right!
we have code like below:
String sql = "select id,title,url,singer,view,info from cache where id=" + id;
SQLiteDatabase db = getMaintainer().getReadableDatabase();
Cursor query = db.rawQuery(sql, null);
query.moveToFirst();
while(query.moveToNext()){
DBMusicData entity = new DBMusicData();
entity.setId(query.getString(query.getColumnIndex(FIELD_ID)));
entity.setTitle(query.getString(query.getColumnIndex(FIELD_TITLE)));
entity.setSinger(query.getString(query.getColumnIndex(FIELD_SINGER)));
entity.setTitlepic(query.getString(query.getColumnIndex(FIELD_PICURL)));
entity.setInfoUrl(query.getString(query.getColumnIndex(FIELD_INFO)));
entity.setViews(query.getString(query.getColumnIndex(FIELD_VIEW)));
Log.w(tag, "cache:"+ entity.toString());
}
query.close();
query=null;
db.close();
db=null;
If we have only one record in the cache table, query.moveToFirst(); will cause that no record returns.
I am using custom adapter extending cursor adapter for displaying data in listview, to display particular phone number i have passed the id to a method in database class but it is showing
errorandroid.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
while placing debugger in the the method it is not going after the line
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
Can any one help me to solve it.
This is the code:
public String getNumberFromId(int id)
{
String num;
db= this.getReadableDatabase();
Cursor cursor = db.query(scheduletable, new String[] { "ContactNumber" },"_id="+id, null, null, null, null);
cursor.moveToFirst();
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
cursor.close();
db.close();
return num;
}
Whenever you are dealing with Cursors, ALWAYS check for null and check for moveToFirst() without fail.
if( cursor != null && cursor.moveToFirst() ){
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
cursor.close();
}
Place logs appropriately to see whether it is returning null or an empty cursor. According to that check your query.
Update Put both the checks in a single statement as mentioned by Jon in the comment below.
Update 2 Put the close() call within the valid cursor scope.
try this.. this will avoid an Exception being thrown when the cursor is empty..
if(cursor != null && cursor.moveToFirst()){
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
cursor.close();
}
First check this Condition before fetching data
if(cursor!=null && cursor.getCount()>0){
cursor.moveToFirst();
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
}
Check the return value from moveToFirst(), before you try to read anything from the cursor. It looks as if no results are being returned.
a save schema to query Cursors is
// just one
Cursor cursor = db.query(...);
if (cursor != null) {
if (cursor.moveToFirst()) {
value = cursor.getSomething();
}
cursor.close();
}
// multiple columns
Cursor cursor = db.query(...);
if (cursor != null) {
while (cursor.moveToNext()) {
values.add(cursor.getSomething());
}
cursor.close();
}
In case people are still looking:
Instead of searching for "ContactNumber" try searching for Phone.NUMBER. The tutorial has the code with more details: http://developer.android.com/training/basics/intents/result.html
try to uninstall the app and then again test it... actually the sqlite db is created only once when the app is first install... so if you think your logic is current then reinstalling the app will do the trick for you. !!!!