Android SQLite column value does not exists issue - android

need help in some wired problem. I have a sqlite table items as following
item_id item_name
1 first
2 second
3 third
and so on
this piece of code is inserting item_id and item_name to arrays perfectly fine. But when i assign it to CustomCursorAdapter it through exception
"column 'first' does not exists"
please help I am newbie to Android.
c = db.rawQuery("select item_id as _id, item_name from items", null);
int i = 0;
c.moveToFirst();
do {
from[i] = c.getString(1);
to[i] = c.getInt(0);
Log.i("item ", to[i] + " " + from[i]);
i++;
} while (c.moveToNext());
try {
CustomCursorAdapter ca = new CustomCursorAdapter(this,
android.R.layout.simple_list_item_1, c, from, to);
getListView().setAdapter(ca);
} catch (Exception e) {
Log.e("Ex ", e.getMessage()); // exception : column 'first' does not exists.
}

This is because you are setting from[0] = c.getString(1).
getString() is zero-based so in your case is returning "first". Then you are passing from as the from parameter of a class (that I guess, extends SimpleCursorAdapter) and then you are receiving this error when the adapter is trying to map this column name. In this case from represents the list of column names holding the data to bind to the UI, which is represented by to.

in from parameter in
CustomCursorAdapter ca = new CustomCursorAdapter(this,
android.R.layout.simple_list_item_1, c, from, to);
needed column names as arguments, whereas you are passing column values array to from array, whereas 'to' needed to be id of textviews of layouts these columns to de projected, so in this example id is android.R.id.textview1, so do following:
String[] from= new String[]{"item_name"};
int[] to= new int[]{android.R.id.textView1};
and then execute your query on these parameters.

Related

Get value of the Foreign Key in SimpleCursorAdapter

I have a listView populated with data from my db. I use a simpleCursorAdapter to show the values.
I have a table where i can add lessons : English, french...
In another table, i can create lessons developped (i add date of beginning and end, which days, a theme for the lesson). I must provide the lesson as a FK.
When I add a lesson, in my listView i want to show per example : English - Reading, but it shows 1 - Reading. Because 1 is the value i store in my 2nd table.
How can I change 1 to English ?
Here's my code :
Cursor cursor = dbhelper.getAllCours();
String[] from = { "branche_cours", "designation" }; //here 'branche_cours' is the lesson i store as an INT, it's the FK so
int[] to = { R.id.text_branche_cours, R.id.text_designation };
adapter = new SimpleCursorAdapter(this, R.layout.list_row, cursor, from, to, 0);
lvCours.setAdapter(adapter);
adapter.notifyDataSetChanged();
The method i use getAllCours()
public Cursor getAllCours()
{
//from here, i retrieve the ID, designation and branche_cours
String Query = ("select ID as _id, date_debut, date_dernier, dixieme_point, " +
"demi_point, description, designation, lundi, mardi, mercredi, jeudi," +
" vendredi, samedi, branche_cours from " + TABLE_COURS);
Open();
Cursor cursor = db.rawQuery(Query, null);
return cursor;
}
How can I link that int to the real value ( so how can the '1' become 'English')?
One solution would be to perform an SQL JOIN operation to fetch the data from both tables:
So the SQL query should be something thing like:
SELECT table1.branche_cours, table2.designation
FROM table1
INNER JOIN table2 ON table1.ID=table2.ID;
To look up a value in another table, you can use a correlated subquery:
SELECT ID AS _id,
...,
samedi,
(SELECT name
FROM other_table
WHERE other_table.id = cours.branche_cours
) AS branche_cours
FROM cours;

Android - populate ListView SQLite, cursor null pointer

I have two tables atm, users and notes. I am trying to retrieve data that belongs to the user. So all data to list must be owned by the original user and shown only to him. I have made my table in Databasehelper.
I have made a new class that controls the notes table. In listNotes() I want to loop through the cursor row and get all data owned by the user. Am I quering it correctly?
// Listing all notes
public Cursor listNotes() {
Cursor c = db.query(help.NOTE_TABLE, new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
db.close();
return c;
}
I then want to display the cursor data collected in a listview
public void populateList(){
Cursor cursor = control.listNotes();
getActivity().startManagingCursor(cursor);
//Mapping the fields cursor to text views
String[] fields = new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE};
int [] text = new int[] {R.id.item_title,R.id.item_body, R.id.item_date};
adapter = new SimpleCursorAdapter(getActivity(),R.layout.list_layout,cursor, fields, text,0);
//Calling list object instance
listView = (ListView) getView().findViewById(android.R.id.list);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
You aren't creating the NOTE_TABLE right.
You miss a space and a comma here
+ COLUMN_DATE + "DATETIME DEFAULT CURRENT_TIMESTAMP"
It has to be
+ COLUMN_DATE + " DATETIME DEFAULT CURRENT_TIMESTAMP,"
There are two issues here:
One is you have missed a comma (after the Timestamp as specified in an earlier answer).
The other error you have is when using a SimpleCursorAdapter, you need to ensure that the Projection string array includes something to index the rows uniquely and this must be an integer column named as "_id". SQLite already has a feature built in for this and provides a column named "_id" for this purpose (however you can have your own integer column which you can rename to _id). To solve this, change your projection string array to something like:
new String[] {"ROW_ID AS _id", help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}
I guess the NullPointerException stems from this (but without the stacktrace I don't know for sure).

Could not read row 0, col -1 from CursorWindow

I know this question has been asked a number of times but for some reason I can't solve it.
I am 100% sure that there is no problem in the column name.
This is the table definition:
CREATE TABLE IF NOT EXISTS categories (category_id INTEGER, category_name TEXT, PRIMARY KEY(category_id))
This is the access to the column.
As can be seen I do a small test first to make sure I have the correct column name.
Using the name I print to the LogCat the value of the column in the first row.
It works perfectly. Yet, when passed to the adapter I get the above error.
Cursor mGroupsCursor = _dbHelper.fetchGroup();
getActivity().startManagingCursor(mGroupsCursor);
mGroupsCursor.moveToFirst();
String colName = "category_name";
Log.d("ToratYavneh", "i = " + i + " category_name = " + mGroupsCursor.getString(mGroupsCursor.getColumnIndex(colName)));
ExpandableListView elv = (ExpandableListView) view.findViewById(R.id.list);
MyExpandableListAdapter adapter = new MyExpandableListAdapter(mGroupsCursor, getActivity(),
R.layout.rowlayout_category, // Your row layout for a group
R.layout.rowlayout_sub_category, // Your row layout for a child
new String[] { colName }, // Field(s) to use from group cursor
new int[] {R.id.category_name }, // Widget ids to put group data into
new String[] { "sub_category_name" }, // Field(s) to use from child cursors
new int[] { R.id.sub_category_name }); // Widget ids to put child data into
elv.setAdapter(adapter);
I thought that maybe the problem was in the child but it never reaches getChildrenCursor.
Here is the code for the cursor:
public Cursor fetchGroup() {
String query = "SELECT * FROM categories";
return _database.rawQuery(query, null);
}

How to get SQLite database Column values as List in android

I have three column, first id, second title and third body.
Like this
id title body
1 t1 b1
2 t2 b2
3 t3 b3
So, I want to get title and display in list with listview and if I click t2 title then display body of respective clickable title.
What i did.
DatabaseHelper.java
public Cursor retriveTitle(String [] title) {
Cursor c = null;
c = myDataBase.rawQuery(
"select id,title from book,", title);
return c;
}
Main.java
private void displayTitle() {
try {
myDataBase = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
Cursor cursor = myDataBase.rawQuery("SELECT b.id, b.title FROM book b ", new String[] { "" });
String test=cursor.getString(cursor
.getColumnIndex("title"));
//How to display title of book in listview
}
getting this:
01-18 14:20:03.401: E/AndroidRuntime(6704): Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
I am using already database file, according to this blog post: Using your own SQLite database in Android applications
Try out
Cursor cursor = myDataBase.rawQuery("SELECT b.id, b.title FROM book b",null);
curosr.moveToFirst();
String test=cursor.getString(cursor
.getColumnIndex("title"));
I think your query should use a "where" statement
c = myDataBase.rawQuery("select id,title from book where title=?", title);
Of course you want to pass a certain number of arguments
c = myDataBase.rawQuery("select id,title from book where title in (?, ?, ?)", new String[]{title1, title2, title3});
But then if the number of title can vary, you will need to dynamically create a string with enough question marks. See this post
IN clause and placeholders
If you still get en error, maybe providing more log could help. Also if the lo say what line fails, tell which one it is. we can't see line numbers here
Good luck
Here's how it worked out for me. In an other class, I have created a method of List type and added the column id & the name of the item in the list from the sqlite database.
Here's the piece of code to retrieve the column id of the selected item.
public List<String> list;
adapt = new MyAdapter(this, R.layout.list_inner_view, list); //custom adapter
listTask.setAdapter(adapt);
listTask.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int position, long l) {
Integer id = list.get(position).getId();
//position is the position of the item in the list.
}
});
Result: the item is at 3rd position in the list. Its database column_id (auto increment) value is 12 because I have deleted previous items. So the result you expect is 12, which is the value of variable id.
If you don't understand this fully, it may be because I haven't posted my entire code. But I'll help you out with your problem.

Unable to show data in Gridview in Android ! please help me out

I am entering some values in to my SQLlite database and then retrieving them in a gridview.I am getting a Error "column'_id'" does not exist.but I have not used any _id named column in the database. How can I make it work?? I think theres some problem with SimpleCursor Adapter .
GridView gv = (GridView)findViewById(R.id.gridView1);
try
{
db1 = openOrCreateDatabase("record.db", Context.MODE_PRIVATE,null);
db1.execSQL("CREATE TABLE IF NOT EXISTS stu(ID INTEGER primary Key,NAME VARCHAR foriegn key,age VARCHAR);");
db1.execSQL("INSERT INTO stu VALUES (1,'mona','123');");
Cursor c = db1.rawQuery("SELECT * FROM stu", null);
if(c!= null){
if (c.moveToFirst()) {
do {
String[] cols = new String[]{c.getString(c.getColumnIndex("ID")),c.getString(c.getColumnIndex("NAME"))};
int[] views = new int[] {R.id.textView1,R.id.textView2};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
c, cols, views);
gv.setAdapter(adapter);
}while(c.moveToNext());}
}} catch(Exception e){
Toast.makeText(getBaseContext(),"errord"+ e.getMessage(), Toast.LENGTH_LONG).show();
}
}
The documentation for CursorAdapter (which SimpleCursorAdapter extends) states:
The Cursor must include a column named "_id" or this class will not work.

Categories

Resources