I have been trying to work out the bug on this but can't seem to find what I'm looking for search Google for the past few days, i have hit and missed on stuff that is leaning towards what i want to do but haven't ran across anything that is what i am trying to do.
To start off, I built my SQLite DB along with "TheNewBoston Android Tuts" everything works fine, now that I am trying to change the view database around it errors out or crashes the app at start up. I am wanting to display certain columns in a row from the DB with the Cursor using the for loop and to dynamically load the TableView with the data:
DbEntry[ data | data| Displayed | data | Display | Display | data ]
I can do this if i have a TextView off on its own but with it in a TableLayout>TableRow i think that's where the problem is but not sure... would like to be able to load the table rows from the class its self instead of setting the text views if possible. I hope i gave enough info on what i am trying to do, if anyone can point me to a really good tutorial or give some light on this, it wold be greatly appreciated.
XML:
<TableLayout
android:id="#+id/view_Table"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="5" >
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="4" >
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
<TextView
android:id="#+id/view_DbCol3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="DB Col 3 Displayed Data" />
</TableRow>
with xml i hope i am doing the table right that its similar to hmtl kind of things by putting table rows in side one another
SQLview Class
setContentView(R.layout.sqlview);
TextView tv = (TextView) findViewById(R.id.view_DbCol3);
try {
DBload info = new DBload(this);
info.open();
String data = info.getData();
info.close();
tv.setText(data);
} catch (Exception e) {
// Error Message Dialog
String error = e.getLocalizedMessage();
Dialog d = new Dialog(this);
d.setTitle("DB ERROR");
TextView tv1 = new TextView(this);
tv1.setText(error);
d.setContentView(tv1);
d.show();
}
DbHelper Class: getData Method
public String getData() {
String[] cols = new String[] {KEY_PLACE};
// I have also tried with all my KEY variables
// reads info from DB columns
Cursor c = ourDB.query(KEY_TABLE, cols, null, null, null, null, null);
String result = "";
int Ione = c.getColumnIndex(KEY_PLACE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result
+ c.getString(Ione)
+ "\n";
}
return result;
}
the error i am getting is
11-17 00:13:09.993: E/CursorWindow(590): Bad request for field slot 0,-1. numRows = 2, numColumns = 1
like i said i hope i have given enough information for little help if possible, thanks alot
This link will help you alot.
anywayz try this in you code
if(c.getCount()>0) {
int index=0;
while(c.moveToNext()){
result = result
+ c.getString(index)
+ "\n"; `enter code here`
index++;
}
}
Hope this helps..
The error seems to say that your column 'KEY_PLACE' doesn't exists, because the columnIndex method returns -1.
Check the value of KEY_PLACE and the name of the column returned in your cursor
Hope it helps
Jokahero
PS: You should check that your cursor is not null before using it:
if (c != null) {
while (c.moveToNext()) {
// ...
}
}
And also don't forget to close your cursor when the job is finished:
c.close();
Related
Why doesnt my Android Cursor go all the way to the end of the original "promise"??
My cursor.getCount() differs from my last cursor.getPosition(). Check my while loop! It is all I do with it!
Notes:
1. it is about querying the Contacts content provider (android api >5)
2. I display only the esential code
Cursor cursor = mContext.getContentResolver().query(mUri, mProjections, null, null, null);
Logger.d(TAG, "*** cursor.getCount(): "+cursor.getCount());
while (cursor.moveToNext()) {
Logger.d(TAG, "| position: "+cursor.getPosition());
processMainCursor(serializer, cursor);
}
cursor.close();
processMainCursor() will display data from cursor + do another queries: one 4 phones, one 4 emails, one 4 IM accounts:
void processMainCursor(XmlSerializer serializer, Cursor main_cursor) {
writeCursorData(serializer, main_cursor); //writes cursor data, column by column
writePhoneEntities(serializer, main_cursor);
writeEmailEntities(serializer, main_cursor);
writeIMEntities(serializer, main_cursor);
}
In none of my writeXXX methods do i close my main_cursor or move next!!!..have to trust me on that.. i just do a new query, print data & close that cursor
So statistics:
cursor.getCount() = 695 (always)
commenting writePhoneEntities, writeEmailEntities, writeIMEntities: cursor.getCount() =
last cursor.getPosition() = 695 (so correct!)
leaving one/two/all of my writeXEntities shows randomness; example: leaving them all:
last cursor.getPosition() sometimes displays 254, 257, 253, etc; leaving just phone & IM: 514, 510, 511, etc (so different RUN -> different last cursor.getPosition() VALUE)
So oppinions.. Why is that? Is it memory related?
Update:
Leaving any of my writeXEntities displays at the end in logcat:
Removing dead content provider: contacts
Update 2
Adding cursor.moveToFirst(); & doing loop like
do {
//do whatever you want
} while (cursor.moveToNext());
didn't do the job..
So maybe the answer is in this logcat entries:
05-21 23:29:30.209: I/ActivityThread(7085): Removing dead content provider: contacts
05-21 23:29:30.209: I/ActivityThread(7085): Removing dead content provider: com.android.contacts
SAMPLE OF a writeXEntity REMOVED
SOLUTION .. i wasnt closing the cursors from writeXEntity corectly (probably leaving quite a lot of open cursor after main while)
in reality i was closing like this
if(phone_cursor!=null && phone_cursor.getCount() > 0)
{
//... stuff
phone_cursor.close();
}
i should have closed after if
if(phone_cursor!=null && phone_cursor.getCount() > 0)
{
//... stuff
}
phone_cursor.close();
I guess leaving a basilion cursor open ..was the answer?!?
You need to move the cursor to the first row. Try adding cur.moveToFirst() before the while loop.
You might also consider using a do-while loop. This will ensure that you never skip over the first row in the cursor:
if (cursor.moveToFirst()) {
do {
//do whatever you want
} while (cursor.moveToNext());
}
cursor.close();
Well, they won't be the same number as the getCount is the number of items, and the position is the position, ( the first one being 0). So the final position should always be one less than the count.
If it's something other than that, I guess I'm not understanding your question properly.
Use cursor as shown below:
if(cursor.getCount() == 0)
{
//No entry found
}
else {
cursor.moveToFirst();
do {
//do whatever you want
} while (cursor.moveToNext());
cursor.close();
After reading the answer you already found (problem with closing cursors) I think that the best way to ensure you close them all is with this code:
Cursor c = null;
try {
c = <your query>;
if (c.moveToFirst()) { // No point in doing more if empty.
do {
<process this cursor row>
} while (c.moveToNext());
}
}
finally {
if (c != null) c.close(); // Not sure the check needed, maybe if query was really wrong.
}
I want to display all my records that are stored in the database
c = db.DBhelper.getChamp1(c.getCount);
//startManagingCursor(c);
int j = 0;
stateNameArray = new String[c.getCount()];
c.moveToFirst();
while(!c.isAfterLast()) {
stateNameArray[j] = c.getString(0);
j++;
Log.i("DEBUG_SQL","" + c.getString(0)+ " "+c.getString(j));
c.moveToNext();
}
//String resultat = ;
Log.i("DEBUG_SQL","" + c.getColumnIndex("article"));
I get an error when I write c.getCount – why? When I write a number like 1 or 2 or 3... that works.
And if I write
c = db.rawQuery("SELECT * FROM loan", null);
I get an error, but if I write
db.rawQuery("SELECT * FROM loan WHERE _id=1", null);
That works. Why?
At the very least, I see a problem with this log statement, where c.getString(j) doesn't make sense. And it may trigger an error as j gets larger.
Log.i("DEBUG_SQL","" + c.getString(0)+ " "+c.getString(j));
What data did you intend to access with the statement c.getString(j)?
On the getCount error. I assumed the error in the following was a typo. But is this where the error associated with getCount was located?
c = db.DBhelper.getChamp1(c.getCount);
But I shouldn't assume - you never know. It should read (add brackets to the method call).
c = db.DBhelper.getChamp1(c.getCount());
And as #Barak mentioned, what is going on with this statement?
To answer the question about your getCount isuue, you get the error because of this:
c = db.DBhelper.getChamp1(c.getCount);
You're trying to get the count of the cursor before you have it (and you're missing ()).
This would work since you have a cursor to count before you pull the next one:
c = db.getSomeCursor;
c1 = db.DBhelper.getChamp1(c.getCount());
Let us know what you're trying to achieve (I can't figure it out from the code you posted) and maybe we can be more helpful.
In my android project, i have saved camera snapshots along with some description in a SQLite database. Now i want to retrieve all those images plus the description one by one and view them in a xml layout that i have created.
here is my xml layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/showTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Data" />
<ImageView
android:id="#+id/showIv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/marker_default"
/>"
</LinearLayout>
</LinearLayout>
i tried following code snippets seperatly,
String[] columns = new String[]{"_id", "name","description","image"};
Cursor c = myDb.query(DATABASE_TABLE, columns, null, null, null, null, null);
if (c.getCount()>0){
c.moveToNext();
byte[] data = c.getBlob(c.getColumnIndex("image"));
return data;
}else{
return null;
//i converted the byte array to bitmap and displayed on the layout
String result = "";
int iname= c.getColumnIndex("name");
int ides= c.getColumnIndex("description");
TextView tv = (TextView) findViewById(R.id.showTv);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result += c.getString(iname) + c.getString(ides);
}
return result;
but i want to get both image and the description together for ALL the data.
please suggest me a method to all the Images and description one by one.
Thank you...
The layout you made won't support more than one Image. Since there is only one ImageView. Unless you want to do a lot of image manipulation, that is. So you should choose an View that fits your needs. I would look at the Gallery widget or ListView widget. Then you need to create a cursor adapter that will adapt the data from your database to your Gallery or Listview widget.
Take a look at:
listview with sqllite
I have a problem with Cursors.
I have 3 tables in my DB : facture (means invoice), vehicule (vehicle) and garage.
An invoice concerns one vehicle and one garage. When I create an invoice, I select the vehicle and the garage from spinners.
When I want to update an invoice, I need to set the item selected in these spinners.
Here is how I do :
for (int iVhc = 0; iVhc < spListeVhc.getCount(); iVhc++) {
Cursor valueVhc = (Cursor) spListeVhc.getItemAtPosition(iVhc);
long idVhc = facture.getLong(facture.getColumnIndexOrThrow("TB_VEHICULE._id"));
long idSpVhc = valueVhc.getLong(valueVhc.getColumnIndex("TB_VEHICULE._id"));
if (idSpVhc == idVhc) {
spListeVhc.setSelection(iVhc);
}
}
for (int iGar = 0; iGar < spListeGar.getCount(); iGar++) {
Cursor valueGar = (Cursor) spListeGar.getItemAtPosition(iGar);
long idGar = facture.getLong(facture.getColumnIndexOrThrow("TB_GARAGE._id"));
long idSpGar = valueGar.getLong(valueGar.getColumnIndex("TB_GARAGE._id"));
if (idSpGar == idGar) {
spListeGar.setSelection(iGar);
}
}
It works for the garage, but the problem is that, for a reason that I don't understand, the spinner of vehicles takes the same ID than the garage.
That means, if the garage selected has the ID 2 in the DB, the selected vehicle will be the vehicle with ID 2 too.
??
Here is my query to get the invoice:
public Cursor recupFacture(long idFacture){
return db.rawQuery("SELECT TB_FACTURE._id, libelle_fa, date_fa, nom_vhc, kilometrage_fa, nom_garage, remarque_fa, date_paie_fa, montant_fa, TB_VEHICULE._id, TB_GARAGE._id" +
" FROM TB_FACTURE, TB_VEHICULE, TB_GARAGE" +
" WHERE fk_vhc_fa = TB_VEHICULE._id" +
" AND fk_gar_fa = TB_GARAGE._id" +
" AND TB_FACTURE._id ="+idFacture, null);
}
And I realised that I have thi kind of mistakes in my log :
08-10 12:54:22.431: ERROR/Cursor(17072): requesting column name with table name -- TB_VEHICULE._id
And same for garage...
Thanks for your help!
EDIT :
I found a solution.
I replaced the TB_GARAGE._id and TB_VEHICULE._id by the fk at the lines :
long idVhc = facture.getLong(facture.getColumnIndexOrThrow("TB_VEHICULE._id"));
long idGar = facture.getLong(facture.getColumnIndexOrThrow("TB_GARAGE._id"));
However, I can't really explain why it works like this but not with the ID.
The prefix of the table causes a strange mistake...
Are you saving the invoice correctly? Make sure you are not accidentally saving the garage ID as vehicle ID as well.
Otherwise, how is "fracture" defined? Perhaps there is a mistake there.
Could someone please help me to understand why the following block of code keeps throwing this error? It's driving me crazy trying to debug this.
public int getContactsCountByGroupId(int id) {
Cursor c = db.rawQuery("SELECT COUNT(*) AS total FROM msg_group_lu WHERE group_id = ?", new String[] {String.valueOf(id)});
DatabaseUtils.dumpCursor(c);
int retval = c.getInt(c.getColumnIndex("total"));
return retval;
}
The dump seems to indicate this;
0 {
total=0
}
This is telling me that there is data in column 0, but yet everytime it tries to execute the line with this code;
int retval = new Integer(c.getInt(c.getColumnIndex("total")));
It gives me this error;
CursorIndexOutOfBoundsException: Index -1 requested, with size of 1
I have tried everything I can think of to try to fix this and am completely stumped. :(
I hope someone knows what causes this.
try writing c.moveToNext(); before executing the line
int retval = c.getInt(c.getColumnIndex("total"));
The cursor position is now -1. after executing the moveToNext command it comes to 0th position.