Dynamic spinner using a SQLite Database - sql

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});

Related

TAG= 'Token line number = 1,Token line offset = 29,Token in error = FROM ' ... insert data from one column to another column of other table

Well... I have two tables named : "chefs" and "cust_Data".
I want to :
Put comments from cust_Data that are being posted into the comment column in chefs table.
By being posted means-> M giving a comment section so that customers will put their comments in "comment" column in "cust_Data" and as soon as those comments are in cust_Data...
Put those comment in "comments" column in "chefs" table.
RAZOR CODE:
#{
var db = Database.Open("vendors");
var selectCommand = "SELECT dish FROM chefs WHERE ID= #0";
var chefID = Request.QueryString["chefid"];
var selectedData = db.Query(selectCommand, chefID);
var dishName=Request.QueryString["dish"];
var chefName=Request.QueryString["chefName"];
var comments=Request["SELECT comments from chefs"]; //IMPORTANT
var ID=Request["SELECT ID from chefs"]; //IMPORTANT
var grid = new WebGrid(source: selectedData, rowsPerPage: 10);
Validation.RequireField("cust_fname", "You must enter your firstname");
Validation.RequireField("cust_lname", "You must enter your surname");
Validation.RequireField("cust_email", "You haven't entered a valid Email_ID");
Validation.RequireField("rating", "Rating is required");
Validation.RequireField("comment", "Please provide your Comment about Respective Homeschef");
var cust_fname = "";
var cust_lname= "";
var cust_email= "";
var rating= "";
var comment= ""; //IMPORTANT
if(IsPost && Validation.IsValid() && chefID.AsInt()!=0){
cust_fname = Request.Form["cust_fname"];
cust_lname = Request.Form["cust_lname"];
cust_email = Request.Form["cust_email"];
rating = Request.Form["rating"];
comment = Request.Form["comment"]; // IMPORTANT->TAKING COMMENT FROM USER
var insertCommand = "INSERT INTO cust_Data (cust_fname, cust_lname, cust_email, dish, chef_ID, rating, comment) Values(#0, #1, #2, #3, #4, #5, #6)";
db.Execute(insertCommand,cust_fname,cust_lname, cust_email, dishName, chefID, rating, comment); // EXECUTED SUCCESSFULLY IN cust_Data
var insert= "INSERT INTO chefs(comments) FROM cust_Data(comment) WHERE chefs(ID)=cust_Data(chef_ID) Values(#0,#1,#2,#3)"; //IMPORTANT
db.Execute(insert,comments,comment,ID,chefID); // IMPORTANT -> ERROR OCCURED ?????????
}
}
Exception Details: System.Data.SqlServerCe.SqlCeException: There was an error parsing the query. [ Token line number = 1,Token line offset = 29,Token in error = FROM ]
I inserted IMPORTANT TAG(to save your time for important things) from where i took the parameters I needed to parse.
Again, Thank you so much in advance...
Though this is not a complete answer, writing this as a answer as the content for explanation is too long.
Even though you've updated the insert into command, the select statement is still wrong. You are trying to write the select statement using the syntax of insert statement i.e. table_name(column_name) but it should be
SELECT column_name from table_name WHERE table_name.column_name=''
Insert into statement works by taking complete SQL select statement prefixed by Insert Into clause. So, your code should be something like this:
INSERT INTO chefs(comments) SELECT comments from cust_Data WHERE chefs.ID=cust_Data.chef_ID
But this won't work as you've not joined the table chefs and cust_data. So you will have to join both the tables and get the correct records, then use the insert into command to insert the records into the chefs table.
Looking more into your program, it looks like you want to update the existing records from the chefs table, or insert is the correct one? Your chefs table has other columns i.e. ID,dish which have been ignored in the insert statement. I doubt that this insert statement would run properly without these columns.
Also, why are you querying comments and ID values separately. And the rows are also not filtered, so it will fetch all the records from the database.
var comments=Request["SELECT comments from chefs"]; //IMPORTANT
var ID=Request["SELECT ID from chefs"]; //IMPORTANT
The database structure and your agenda that you are trying to achieve looks weird to me. I.e. Customer enters the data in cust_data.comments and you want to move/copy these comments to chefs.comment and as soon as the data comes in cust_data table. Why not directly insert into the chefs table instead of this 2 step approach.
Have you thought about the whole process from start to finish? Have you drawn it on paper or screen using UML diagram/process flow?
It looks like you do not have enough experience on the database side. My suggestion would be that you first try these statements directly on the database tool SSMS, get it confirmed that it's working and then apply it in your program. You can use hard coded values for testing and then substitute with parameters when applying it into the program.
Also it would help you if you can learn Stored Procedures and use that in your program. This will reduce such complications from program side and also reduce the database calls

Get distinct values for a group of fields from a list of records

We are using Liferay (6.2 CE GA4) with Lucene to perform search on custom assets. Currently we can retrieve the proper hits and the full documents.
We want to return a unique combination of certain fields for our custom asset.
To make it more clear, we want to do something similar to the following SQL query but using Lucene in Liferay:
SELECT DISTINCT
field01, field02, field03
FROM
FieldsTable
WHERE
someOtherField04 LIKE "%test%";
ORDER BY
field01 ASC, field02 ASC, field03 ASC;
How we are doing it currently
Currently we are manually fetching field values by iterating through all the documents and then filtering the duplicate combination. This process takes time when there are more than 5k records to process on each request. And the distinct field values would mostly be a few hundred records.
Any help is much appreciated.
Thanks
P.S.: Also cross-posted on Liferay forums: https://www.liferay.com/community/forums/-/message_boards/message/55513210
First you need to create the SearchContext for your query (just as reference):
SearchContext searchContext = new SearchContext();
searchContext.setAndSearch(true);
// Add any specific attributes for your use case below:
Map<String, Serializable> attributes = new HashMap<>();
attributes.put(Field.CLASS_NAME_ID, 0L);
attributes.put(Field.DESCRIPTION, null);
attributes.put(Field.STATUS, String.valueOf(WorkflowConstants.STATUS_APPROVED));
attributes.put(Field.TITLE, null);
attributes.put(Field.TYPE, null);
attributes.put("articleId", null);
attributes.put("ddmStructureKey", ...);
attributes.put("ddmTemplateKey", ...);
attributes.put("params", new LinkedHashMap<String, Object>());
searchContext.setAttributes(attributes);
searchContext.setCompanyId(... the ID of my portal instance ..);
searchContext.setGroupIds(new long[] { ... the ID of the site ... });
searchContext.setFolderIds(new long[] {});
Now you can find the list of all values for one or more specific fields:
// We don't need any result document, just the field values
searchContext.setStart(0);
searchContext.setEnd(0);
// A facet is responsible for collecting the values
final MultiValueFacet fieldFacet = new MultiValueFacet(searchContext);
String fieldNameInLucene = "ddm/" + structureId + "/" + fieldName + "_" + LocaleUtil.toLanguageId(locale);
fieldFacet.setFieldName(fieldNameInLucene);
searchContext.addFacet(fieldFacet);
// Do search
IndexerRegistryUtil.getIndexer(JournalArticle.class).search(searchContext);
// Retrieve all terms
final List<String> terms = new ArrayList<>();
for (final TermCollector collector : fieldFacet.getFacetCollector().getTermCollectors()) {
terms.add(collector.getTerm());
}
At the end terms will contain all terms of your field from all found documents.

Unique values from one column using 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();

Selecting specific columns using linq: What gets transferred?

I refer to this example: Return selected specified columns
Quote:
If BlobDetails isn't the LINQ entity, then you can do it directly:
var qry = from b in dc.Blobs
orderby b.RowVersion descending
select new BlobDetails {
Id = b.Id, Size = b.Size,
Signature = b.Signature, RowVersion = b.RowVersion};
return qry.ToList();
I see that they are selecting specific column in a query through the ORM-tool LINQ TO SQL.
Critics of ORM-tools say that, if I remember correctly, that ORM-tools select and return entire objects from the table, and limits the options of selecting only specific columns as one can do through classic SQL-programming. Of course, I have my doubts about that when I see this example, but nevertheless, I still keep asking myself the question: Does the database return only the selected columns, or does it return the entire objects, leaving the column-filtering to the ORM-tool?
From this example, they also have a class called Blobdetails:
public class BlobDetails
{
public int Id { get; set; }
public string Signature { get; set; }
public int Size { get; set; }
public System.Data.Linq.Binary RowVersion { get; set; }
}
Do I need to create my own classes everytime I only wish to select a few columns from a table through LINQ?
You don't need to create new classes to select few columns from a table. You can use anonymous types for that.
var qry = from b in dc.Blobs
orderby b.RowVersion descending
select new { b.Id, b.Size, b.Signature, b.RowVersion};
return qry.ToList();
Only selected columns are transferred. There is no difference between using plain SQL and using LINQ to SQL. When you are executing LINQ query, it is converted to plain SQL and executed. Then result is mapped to your objects.
You can use SQL Server Profiler to see what query was generated and executed on server. Also you can use LINQPad to see what SQL will be generated from your query. In your case query will be same either you use BlobDetails or anonymous object:
SELECT [t0].[Id], [t0].[Size], [t0].[Signature], [t0].[RowVersion]
FROM [Blobs] AS [t0]
ORDER BY [t0].[RowVersion] DESC
when you do projections LINQ does indeed only select those columns and there is nothing preventing you from materializing it however you want. So in your example code
select new BlobDetails
{
Id = b.Id,
Size = b.Size,
Signature = b.Signature,
RowVersion = b.RowVersion
};
Only b.id, b.size, b.signature, & b.rowversion are selected. You can verify this with sql profiler or your debugger, I seem to recall there is also a function you can call on the datacontext to get the last query that was ran.
I think that the answer to your first question is already in the POST you mentioned. However...
If your BlobDetails is not LINQ entity you can simply use it in your select statement to define (shrink) your projection attributes. For example:
var qry = from b in dc.Blobs
select new BlobDetails { Id = b.Id, Size = b.Size }
would compile to SQL query like SELECT Id, Size FROM Blob ....
But if BlobDetails is LINQ entity you will need to use that AsEnumerable() hack otherwise you will get NotSupportedException: Explicit construction of entity type in query is not allowed.
var qry = from b in dc.Blobs.AsEnumerable()
select new BlobDetails { Id = b.Id, Size = b.Size }
Edit
As #Chris Pitman stated in his comment this AsEnumerable() approach could create serious bottleneck, beacause the whole table would be loaded in memory before applying the projection. So it is not recommended!
To your second question:
You will need to create custom class for objects that you want use easily outside the scope of the method. Properties of an anonymous object are visible only in the scope, where they have been declared and anonymous objects can be cast only to type object.
So if you want to return anonymous objects from method the return type would has to be an enumerable of object or dynamic as #xeondev stated in his comment.
There's no need to create your own classes, you can return an anonymous type. You can write something like this
var qry = from b in dc.Blobs
orderby b.RowVersion descending
select new {
Id = b.Id, Size = b.Size,
Signature = b.Signature, RowVersion = b.RowVersion};
return qry.ToList();
Although the signature of the method should look to something like this
public IEnumerable<object> GetItems()
or
public dynamic GetItems()
So if you are going to use the result of linq query in outer scope like you example suggest, it is highly recommended you create your own classes.

Linq to sql - get value from db function and not directly from the db field (while mapping properties)

When you map a table to an object, every property created corresponds to one db column.
I want to execute a db function on a column before it gets mapped to the property, so the property gets the value returned by the db function, and not the column
I was trying to achieve that by Expression property of ColumnAttribute (as in the example below), so instead of BirthDate the usrFn_UTCToLocalTime(BirthDate) is returned
but it does not seem to be working and still gets pure value of the column.
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_BirthDate", DbType = "DateTime", UpdateCheck = UpdateCheck.Never, Expression = "dbo.usrFn_UTCToLocalTime(BirthDate)")]
public System.Nullable<System.DateTime> BirthDate
{
get
{
return this._BirthDate;
}
}
I have also modified the DBML XML as in:
other post on stackoverflow
but also without result.
Is that possible by using LINQ or do I have to overwrite a getter which costs roundtrip to the server?
According to the Remarks section on this MSDN page, the Expression property of the ColumnAttribute is used when calling CreateDatabase, so it won't work the way you intend unless you created your database with Linq to Sql.
You can create a Linq query that selects the various columns and calls the db function in one statement like this (based on MSDN example):
var qry = from person in db.Persons
select new {
FirstName = person.FirstName,
LastName = person.LastName,
BirthDate = person.BirthDate,
Dob = db.usrFn_UTCToLocalTime(person.BirthDate)
};
This projects into an anonymous type, but you could use a non-anonymous type as well. For the sake of the example, I've got a table named Person with FirstName, LastName, and BirthDate columns, and a user defined scalar function named usrFn_UTCToLocalTime. The sql statement sent to the server is:
SELECT [t0].[FirstName], [t0].[LastName], [t0].[BirthDate], CONVERT(DateTime,[dbo].[usrFn_UTCToLocalTime]([t0].[BirthDate])) AS [Dob]
FROM [dbo].[Person] AS [t0]
As I was suggesting in the question, for now I have overwritten the get method so I have:
get
{
using (var context = DB.Data.DataContextFactory.CreateContext())
{
return context.usrFn_UTCToLocalTime(_BirthDate);
}
//return this._BirthDate;
}
But with every access to the property, roundtrip is made - which is not my intention but gives a proper result.
I leave the question still open