Unique values from one column using ActiveAndroid? - activeandroid

I'm trying to get all unique values from a single column from a table. I'm utterly failing, and the docs don't seem to go into enough depth, and what I've gleaned from looking at the source seems like that should help, but doesn't.
List<Question> questions = new Select().from(Question.class).where("ZCLASSLEVEL = ? ", classLevel).execute();
works to get all the columns of all the Questions.
However,
List<Question> questions = new Select(columns).from(Question.class).where("ZCLASSLEVEL = ? ", classLevel).execute();
doesn't return any data (questions.size() = 0), where I've tried
String[] columns = { "ZHRSSECTION" };
and
Select.Column[] columns = { new Select.Column("ZHRSSECTION", "ZHRSSECTION")};
Presumably, throwing .distinct(). after the Select() should return only unique values, but I can't even get just the single column I'm interested in to get returned.
What am I missing here?
Thanks!
randy

You should use groupBy() method to make the use of distinct() method.
For example:
List<Question> questions = new Select()
.distinct()
.from(Question.class)
.groupBy("ZCLASSLEVEL")
.execute();
The above code returns a list of Questions, one for each ZCLASSLEVEL (probably the last row).
Then you can get the unique values of ZCLASSLEVEL as
for(Question question: questions){
int level = question.ZCLASSLEVEL;
//do something with level.
}

A little late in answering this, but the issue is because SQLiteUtils.rawQuery() makes the assumption that the Id column is always going to be in the cursor result. Set your columns String[] to {Id, ZHRSSECTION} and you'll be fine.
List<FooRecord> list = new Select(new String[]{"Id,tagName"}).from(FooRecord.class).execute();

Related

Dynamic spinner using a SQLite Database

I want my spinner to be dynamically updated from my SQLite database. The spinner should contain months and years (ex. april 2013), from my sqlite database.
I have searched the web a lot, and also many of the questions from this site, but now i can't solve the rest.
Right now my spinner list is getting longer, but there is no text? What is the problem?
Here is the relevant code in my main class
KilometerSQL info = new KilometerSQL(this);
info.open();
String data = info.getData();
final Cursor cSpinner;
cSpinner = (Cursor) KilometerSQL.getSpinnerData();
startManagingCursor(cSpinner);
SimpleCursorAdapter scaYear = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item,cSpinner,new String[] {KilometerSQL.KEY_MONTH},new int[]{});
scaYear.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(scaYear);
info.close();
tvView.setText(data);
And here is my SQLiteDatabase:
public static Cursor getSpinnerData() {
// TODO Auto-generated method stub
return ourDatabase.query(DATABASE_TABLE, //table name
new String[] {KEY_ROWID, KEY_MONTH}, //list of columns to return
null, //filter declaring which rows to return; formatted as SQL WHERE clause
null,
KEY_MONTH, //filter declaring how to group rows; formatted as SQL GROUP BY clause
null, //filter declaring which row groups to include in cursor; formatted as SQL HAVING clause
null); //how to order rows; formatted as SQL ORDER BY clause
}
Don't hesitate to ask questions if you need some info or code.
Thank you very much.
I found the solution..
I needed to add this into the code: android.R.id.text1
like this:
SimpleCursorAdapter scaYear = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item,cSpinner,new String[] {KilometerSQL.KEY_MONTH},new int[]{android.R.id.text1});

Lookup field and Invalid data has been used to update the list item error

I have list A with three columns JobNumber,Crew and Date which is lookup column to List B. When I create three individual lookup fields in List B then following code works fine,
SP.FieldLookupValue lvjobNum = new SP.FieldLookupValue();
lvjobNum.LookupId = ID;
lItem["JobNumber"] = lvjobNum;
SP.FieldLookupValue lvCrew = new SP.FieldLookupValue();
lvCrew.LookupId = ID;
lItem["Crew"] = lvCrew;
SP.FieldLookupValue lvDate = new SP.FieldLookupValue();
lvDate.LookupId = ID;
lItem["Date"] = lvDate;
However when I create lookup field using "Additional column settings" option like,
Then same code shown above doesn't work and it throws an error,
<nativehr>0x80070057</nativehr><nativestack></nativestack>Invalid data has been used to update the list item. The field you are trying to update may be read only.
Any idea ?
(Answered by the OP as an edit to the question. Transcribed here as a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
Fix was simple,
SP.FieldLookupValue flvRDS = new SP.FieldLookupValue();
flvRDS.LookupId = ID;
lItem["RDS"] = flvRDS;

checking if all the items in list occur in another list using linq

I am stuck with a problem here. I am trying to compare items in a list to another list with much more items using linq.
For example:
list 1: 10,15,20
list 2: 10,13,14,15,20,30,45,54,67,87
I should get TRUE if all the items in list 1 occur in list 2. So the example above should return TRUE
Like you can see I can't use sequenceEquals
Any ideas?
EDIT:
list2 is actually not a list it is a column in sql thas has following values:
<id>673</id><id>698</id><id>735</id><id>1118</id><id>1120</id><id>25353</id>.
in linq I did the following queries thanks to Jon Skeets help:
var query = from e in db
where e.taxonomy_parent_id == 722
select e.taxonomy_item_id;
query is IQueryable of longs at this moment
var query2 = from e in db
where query.Contains(e.taxonomy_item_id)
where !lsTaxIDstring.Except(e.taxonomy_ids.Replace("<id>", "")
.Replace("</id>", "")
.Split(',').ToList())
.Any()
select e.taxonomy_item_id;
But now I am getting the error Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator.
How about:
if (!list1.Except(list2).Any())
That's about the simplest approach I can think of. You could explicitly create sets etc if you want:
HashSet<int> set2 = new HashSet<int>(list2);
if (!list1.Any(x => set2.Contains(x)))
but I'd expect that to pretty much be the implementation of Except anyway.
This should be what you want:
!list1.Except(list2).Any()
var result = list1.All(i => list2.Any(i2 => i2 == i));

NHibernate Like with integer

I have a NHibernate search function where I receive integers and want to return results where at least the beginning coincides with the integers, e.g.
received integer: 729
returns: 729445, 7291 etc.
The database column is of type int, as is the property "Id" of Foo.
But
int id = 729;
var criteria = session.CreateCriteria(typeof(Foo))
criteria.Add(NHibernate.Criterion.Expression.InsensitiveLike("Id", id.ToString() + "%"));
return criteria.List<Foo>();
does result in an error (Could not convert parameter string to int32). Is there something wrong in the code, a work around, or other solution?
How about this:
int id = 729;
var criteria = session.CreateCriteria(typeof(Foo))
criteria.Add(Expression.Like(Projections.Cast(NHibernateUtil.String, Projections.Property("Id")), id.ToString(), MatchMode.Anywhere));
return criteria.List<Foo>();
Have you tried something like this:
int id = 729;
var criteria = session.CreateCriteria(typeof(Foo))
criteria.Add(NHibernate.Criterion.Expression.Like(Projections.SqlFunction("to_char", NHibernate.NHibernateUtil.String, Projections.Property("Id")), id.ToString() + "%"));
return criteria.List<Foo>();
The idea is convert the column before using a to_char function. Some databases do this automatically.
AFAIK, you'll need to store your integer as a string in the database if you want to use the built in NHibernate functionality for this (I would recommend this approach even without NHibernate - the minute you start doing 'like' searches you are dealing with a string, not a number - think US Zip Codes, etc...).
You could also do it mathematically in a database-specific function (or convert to a string as described in Thiago Azevedo's answer), but I imagine these options would be significantly slower, and also have potential to tie you to a specific database.

Fetch Single Item Using DataContext

I'm doing the following:
public MyItem FetchSingleItem(int id)
{
string query = "SELECT Something FROM Somewhere WHERE MyField = {0}";
IEnumerable<MyItem> collection = this.ExecuteQuery<MyItem>(query, id);
List<MyItem> list = collection.ToList<MyItem>();
return list.Last<MyItem>();
}
It's not very elegant really and I was hoping there's something a little better to get a single item out using DataContext. I'm extending from DataContext in my repository. There's a valid reason why before you ask, but that's not the point in this question ;)
So, any better ways of doing this?
Cheers
If it is SQL Server, change your SQL to:
SELECT TOP 1 Something FROM Somewhere ...
Or alternatavely, change these lines
List<MyItem> list = collection.ToList<MyItem>();
return list.Last<MyItem>();
into this one:
return collection.First();
myDataContext.MyItem.Where(item => item.MyField == id)
.Select(item => item.Something)
.FirstOrDefault();
The record returned is undefined, since you have no ORDER BY. So it's hard to do an exact translation. In general, though, reverse the order and take the First():
var q = from s in this.Somewhere
where s.MyField == id
orderby s.Something desc
select s.Something;
return q.First();
Relational tables are unordered. So if you don't specify the record you want precisely, you must consider the returned record as randomly selected.