I try to implement a "android.support.v7.widget.SearchView" into my toolBar who should provide some suggestions to the user.
I wished activeAndroid could provide me a way to retrieve a CursorAdapter directly from my query (basically a getAll()).
The following link seems to be deprecated since .toSql() require private access and "Cache" is unresolved.
Any idea?
You can create a Cursor via ActiveAndroid using:
Cursor cursor = ActiveAndroid.getDatabase().rawQuery("SELECT * FROM TABLE", null);
The CursorAdapter you will need to build yourself but is quite easy and the "Defining the Adapter" section of the link you provided should give you what you need to get started.
Please note that ActiveAndroid 3.1.0 does show the .toSql() as public.
One thing you will need to do is make sure your ActiveAndroid db model includes the expected _id column which is not there by default with ActiveAndroid. You'll want to uninstall the app or perform a database migration to see the changes to the underlying db model. Otherwise you may get this error
java.lang.IllegalArgumentException: column '_id' does not exist
Include the expected '_id' column which is not there by default with ActiveAndroid:
#Table(name = "Items", id = BaseColumns._ID)
Request the cursor like this:
public Cursor getCursor() {
String sql = new Select()
.from(Item.class)
.toSql();
String[] params = null;
Cursor cursor = Cache.openDatabase().rawQuery(sql, params);
return cursor;
}
You could then create an adapter like this:
ListAdapter adapter = new SimpleCursorAdapter(context,
android.R.layout.simple_list_item_1,
c, new String[] {"Name"}, new int[] { android.R.id.text1}
);
Related
I'm having a lot of problems trying to get my spinner to fill with data after my application loads. I'm just messing around and made a database for vehicles. So I'm trying to get a spinner to load the database data into it. This is the code I use in a method to attempt to do so, but my spinner is never loaded with my database data.
SQLiteDatabase db = database.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT vehicle_make, vehicle_model, vehicle_year FROM vehicles;", null);
vehicleProfileSpinner = (Spinner) findViewById(R.id.vehicleProfileSpinner);
startManagingCursor(cursor);
String[] columns = {"vehicle_year", "vehicle_make", "vehicle_model"};
int[] theView = {R.id.vehicleProfileSpinner};
SimpleCursorAdapter vpsAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_dropdown_item, cursor, columns, theView);
vpsAdapter.setDropDownViewResource(R.layout.main);
vehicleProfileSpinner.setAdapter(vpsAdapter);
In my case instead of using Simplecursoradapter, I have created array from cursor entries and created ArrayAdapter and set it to list. It worked perfect. Somehow Simplecursor adapter looks for ID field and causing issue,so I ignored it and used Arrayadapter. I will try to update this post with example I posted for other question.
One thing is all you need SimpleCusorAdapter.
I'd like to use a SimpleCursorAdapter with a Spinner.
I found how to return a Cursor.
QueryBuilder<ChoixPointVerification, Integer> qb = choixPointVerificationDao.queryBuilder();
qb.where().eq(FIELD, id);
PreparedQuery<ChoixPointVerification> preparedQuery = qb.prepare();
AndroidCompiledStatement compiledStatement =
(AndroidCompiledStatement)preparedQuery.compile(db, StatementType.SELECT);
Cursor cursor = compiledStatement.getCursor();
return cursor;
But the Spinner require a _id field and I'll only have an object with an id field. I prefer to avoid the rename of the field.
How can I resolve that case ? I really need to associate an id to all spinner field.
I imagined that I can maybe issue a cursor from a rawsql but I din't find how with ormlite. It seems to be possible if I can create a PreparedQuery with a raw sql.
I also read that if I have an AndroidDatabase object I can issue a Cursor object but how can we create an AndroidDatabase with ormlite ?
I'm really open with all the solution
Regards
You can get the underlying Cursor object from ORMLite by using QueryBuilder without having to resort to a raw query. Take a look at this answer:
Android Cursor with ORMLite to use in CursorAdapter
You can do something like the following code:
// build your query
QueryBuilder<Foo, String> qb = fooDao.queryBuilder();
qb.where()...;
// when you are done, prepare your query and build an iterator
CloseableIterator<Foo> iterator = dao.iterator(qb.prepare());
try {
// get the raw results which can be cast under Android
AndroidDatabaseResults results =
(AndroidDatabaseResults)iterator.getRawResults();
Cursor cursor = results.getRawCursor();
...
} finally {
iterator.closeQuietly();
}
Well I just found a solution which seems to be efficient, simple, and compliant with ormlite.
I just have to get an AndroidDatabase with getHelper().getReadableDatabase().
and then use
Cursor cursor = db.query("choixpointverification",
new String[] { "id", "id as _id", "nom" },
"masque = 0 and idPointVerification = " + idPointVerification.toString(),
null, null, null, "tri");
I am storing information on the phone's contacts using a sqlite database.
The fields I am storing are: _id, contact_id, body where _id is the row's id, contact_id is the phone contact's id and body is just a simple text which is the actual information I am storing.
I'm using a SimpleCursorAdapter to map the data to the view, like so:
Cursor cursor = database.fetchInformation(); // fetch info from DB
String[] from = new String[] { CONTACT_ID, BODY };
int[] to = new int[] { R.id.contact, R.id.body };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
getListView().setAdapter(adapter);
What I would actually want is to get the contact name that is associated with this CONTACT_ID, and have that be shown in the view.
I can't seem to find a simple solution. I've tried implementing my own SimpleCursorAdapter and rewriting setViewText(TextView, String) but it didn't work. Also, it just seems overly complicated for such a simple task.
Any help? Thanks.
You really have two options here:
1) You could create a MatrixCursor that contains all the information you wish to bind to your ListView. While its not very difficult to do this, its probably not the most efficient use of memory because you would need to get the name of every contact in your cursor.
2) You could subclass from CursorAdapter. Its pretty simple to implement the appropriate newView and bindView methods. Inside of bindView you would simply query the phone's contact content provider to get the name of the contact currently being bound.
try this
String where=PEOPLE.CONTACT_ID+"="+requiredId;
String[] projection={People.Name};//u only need name right?
int[] to = new int[] {R.id.body };//if body is ur text view
Cursor cursor = getContentResolver().query(People.CONTENT_URI,projection,where,null, null);
ListAdapter adapter=new SimpleCursorAdapter(this,R.layout.row,result,projection,to);
setListAdapter(adapter);
I am fetching the list of tables from the database. I am using this code to get the list of tables:
public void showAllTable()
{
db.execSQL("select name from sqlite_master where type = 'table'");
}
This query execute successful in to the shell window.
Now I want to display that list of tables in Android. How it is possible? I am calling this function from another activity.
Edited:
Thanks to Stack Overflow, I found the answer here.
The usual way to display a list of data is to use a ListView. To do this you will need to do the following:
1: change your db query to db.query instead of db.exec and store the values in a List:
ArrayList<String> tables = new ArrayList<String>();
Cursor mCursor = db.query("sqlite_master", new String[]{"name"}, "type = table",
null,null,null,null);
if (mCursor.getCount() > 0) {
for (mCursor.moveToFirst(), !mCursor.isAfterLast(), mCursor.moveToNext()) {
tables.add(mCursor.getString(0));
}
}
/** Important! always close cursors and DB's */
mCursor.close();
db.close();
return tables;
2: Use a ListView and an ArrayAdapter to display the information. See The Android Tutorial on how to do this.
I am stuck with SimpleCursorAdapter, I am calling my local SQLite DB and putting it into a cursor which then is passed to the SimpleCursorAdapter.
For same reason the Log Cat keeps showing this error below. I have no idea what is going on and I have been working on this for 6 hours, I didn't think SimpleCursorAdapter would be so difficult to understand.
05-28 19:47:27.524: ERROR/AndroidRuntime(9353): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nyneaxis.android.mpg/com.nyneaxis.android.mpg.userInfo}: java.lang.IllegalArgumentException: column '_id' does not exist
setArray();
rec.open();
Cursor c = rec.getAllVeh();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.userinfo, c, new String[]{c.getString(1)}, new int[]{R.id.nameTxtL});
this.setListAdapter(adapter);
rec.close();
//data adapter
public Cursor getAllVeh() {
try{
return db.query(database_table, new String[] { key_rowid, vehicle_name,
year, make, model, style, vin, plate, notes }, null, null,
null, null, null);
}finally{
}
}
Okay I have modified my code to a rawQuery and I get this error again:
05-28 22:41:48.876: ERROR/AndroidRuntime(1359): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nyneaxis.android.mpg/com.nyneaxis.android.mpg.userInfo}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
private static final String db_sel = "SELECT id as _id, vehicle_name FROM vehicle";
public Cursor getAllVeh() {
try{
return db.rawQuery(db_sel, null);
/*return db.query(database_table, new String[] { key_rowid, vehicle_name,
year, make, model, style, vin, plate, notes }, null, null,
null, null, null);*/
}finally{
}
}
See my answer to this question Android: column '_id' does not exist problem. It explains about the need for the _id column and how to alias it if your DB tables don't have a column with that name.
****EDIT:**** To alias the column in the DB which contains 'unique identifiers' you need to use db.rawQuery(...) instead of db.query(...). The db.rawQuery(...) method takes a SQL string which will allow you to alias the column name to '_id' which is required by the adapter. Example...
Cursor c = db.rawQuery("SELECT <my_unique_column_name> as _id, vehicle_name, ... FROM vehicles");
In the above, replace <my_unique_column_name> with the actual name of the column in the vehicles table which contains unique identifiers. Also, use the actual column names for any other columns that you're requesting the data for.
Well, as the error says your database table definition is missing the default _id column that SimpleCursorAdapter expects to use as the ID column. What is your database table defined as? Add the CREATE TABLE statement you are using to your question.
SimpleCursorAdapter relies on the presence of an _id column: if you don't have it then you'll get that error.
Thanks guys for all you help. I managed to do it a different way and it seems to work like a charm. If anyone has any question or suggestions let me know.
Cursor c = rec.getAllVeh();
while (c.moveToNext()) {
String vehName = c.getString(1);
vehInfo.add(vehName);
}
//put information into the addapter for listview
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, vehInfo);
//applies adapter to listview
list.setAdapter(adapter);