SQLIte not displaying all of the results correctly in ListView - sqlite

I am having trouble with displaying the results in the search activity of my app. I wonder where it went wrong.
The aim of the function below is to search the input query of the user and find it in every files listed. But the results only matches one data eventhough the query is also present in the other files. Here is the code.
public void searchFiles(File[] filelist, String query, String querysearch, String[] namesOfFiles){
querysearch = "SELECT * FROM Data WHERE ObjectID = ? ";
int temp2 = filelist.length;
for (int i = (temp2-1); i >= 0; i--) {
if(!(filelist[i].getName().equals("DataObjectDB.db")) && !(filelist[i].getName().endsWith("-journal"))){
temp1 = filelist[i].getName();
namesOfFiles[i] = temp1.replaceAll(".db$", "");
Toast.makeText(getApplicationContext(),"Searching " + query + " in: " + namesOfFiles[i], Toast.LENGTH_SHORT).show();
DatabaseHelper db1 = new DatabaseHelper(getApplicationContext(),namesOfFiles[i]);
SQLiteDatabase sqldb = db1.getWritableDatabase();
cursor = sqldb.rawQuery(querysearch, new String[]{query});
Toast.makeText(getApplicationContext(),cursor.toString(), Toast.LENGTH_SHORT).show();
}
}
final ListView listView = (ListView) findViewById(R.id.results_listview);
SearchAdapter adapter = new SearchAdapter(this, R.layout.results_column, cursor,0 );
listView.setAdapter(adapter);
}
The searchFiles() function passes the filelist, query, querysearch and namesOfFiles where 1) filelist contains the list of files in the source folder 2) query is the user input he/she wants to search 3) querysearch is the select statement 3) namesofFiles is just an empty string.
I indicate a toast to see if the code traverses through all the folders. And yes it is. But I don't know why it is not displaying all the results.
Any help? Thanks!

Found an answer on different posts. Basically, you just have to use hashmap and arraylist first before setting up the adapter directly.

Related

Sorting Gridview with Entity Framework Not Working as Intended

I have a gridview that i want to sort. I wrote the following method for it:
private void SortGridView(string sortExpression, string direction)
{
var constr = new AdminRequirementEF();
string sort = string.Concat("it.", sortExpression, " ", direction);
int pageSize = Convert.ToInt32(ddPageSize.SelectedItem.Text);
var results = constr.Projects;
int totalRecords = results.Count();
this.PopulatePager(totalRecords, pageIndex);
var sortedResults = constr.Projects.OrderBy(sort).Skip((pageIndex - 1) * pageSize).Take(pageNum).ToList();
grdMain.DataSource = sortedResults;
grdMain.DataBind();
}
The problem is sorting is applied on totalrecords not on per page filtered records. I want to use OrderBy(sort) after applying skip and take but it gives me an error stating skip can not be applied before orderby clause. Any help will be much appreciated.
You can get the constr.Projects collection sorted on its primary key
var results = constr.Projects.OrderBy(p => p.ProjectId)
and then apply the skip and take on the 'results' collection with sorting.
results = results.Skip((pageIndex - 1) * pageSize).Take(pageNum).OrderBy(sort).ToList();
This way you will get the records for particular page sorted as required.

Depending source for drop down list

I have one drop down list in my pages that its source comes of below code. Now I like to put 1 text box adjusted on my drop down list and when I type on that, source of drop down list (DocumentNo) depend on what I type in the text box and when text box is null drop downs list shows all the (DocumentNo) , please help how I have to change my code,
protected void ddlProjectDocument_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var query = from p in _DataContext.tblDocuments
orderby p.DocumentNo
select p;
int maxs = 0;
foreach (tblDocument v in query)
{
if (v.DocumentNo.Length > maxs)
maxs = v.DocumentNo.Length;
}
foreach (tblDocument vv in query)
{
string doctitle = vv.DocumentNo;
for (int i = vv.DocumentNo.Length; i < maxs; i++)
{
doctitle += " ";
}
doctitle += " | ";
doctitle += vv.TITLE;
// Use HtmlDecode to correctly show the spaces
doctitle = HttpUtility.HtmlDecode(doctitle);
ddlProjectDocument.Items.Add(new ListItem(doctitle, vv.DocId.ToString()));
}
}
First, I would highly recommend storing the result of that query at the beginning of the method into something like a session variable so that you don't have to continually query the database every time you hit this page.
Second, you should use the OnTextChanged event in ASP.NET to solve this problem. Put in the OnTextChanged attribute to point to a method in your code behind that will grab the query result values (now found in your session variable) and will reset what is contained in ddlProjectDocument.Items to anything that matched what was being written by using String.StartsWith():
var newListOfThings = queryResults.Where(q => q.DocumentNo.StartsWith(MyTextBox.Value));
At this point all you need to do is do that same loop that you did at the end of the method above to introduce the correct formatting.

Retrieve Cellset Value in SSAS\MDX

Im writing SSAS MDX queries involving more than 2 axis' to retrieve a value. Using ADOMD.NET, I can get the returned cellset and determine the value by using
lblTotalGrossSales.Text = CellSet.Cells(0).Value
Is there a way I can get the CellSet's Cell(0) Value in my MDX query, instead of relying on the data returning to ADOMD.NET?
thanks!
Edit 1: - Based on Daryl's comment, here's some elaboration on what Im doing. My current query is using several axis', which is:
SELECT {[Term Date].[Date Calcs].[MTD]} ON 0,
{[Sale Date].[YQMD].[DAY].&[20121115]} ON 1,
{[Customer].[ID].[All].[A612Q4-35]} ON 2,
{[Measures].[Loss]} ON 3
FROM OUR_CUBE
If I run that query in Management Studio, I am told Results cannot be displayed for cellsets with more than two axes - which makes sense since.. you know.. there's more than 2 axes. However, if I use ADOMD.NET to run this query in-line, and read the returning value into an ADOMD.NET cellset, I can check the value at cell "0", giving me my value... which as I understand it (im a total noob at cubes) is the value sitting where all these values intersect.
So to answer your question Daryl, what I'd love to have is the ability to have the value here returned to me, not have to read in a cell set into the calling application. Why you may ask? Well.. ultimately I'd love to have one query that performs several multi-axis queries to return the values. Again.. Im VERY new to cubes and MDX, so it's possible Im going at this all wrong (Im a .NET developer by trade).
Simplify your query to return two axis;
SELECT {[Measures].[Loss]} ON 0, {[Term Date].[Date Calcs].[MTD] * [Sale Date].[YQMD].[DAY].&[20121115] * [Customer].[ID].[All].[A612Q4-35]} ON 1 FROM OUR_CUBE
and then try the following to access the cellset;
string connectionString = "Data Source=localhost;Catalog=AdventureWorksDW2012";
//Create a new string builder to store the results
System.Text.StringBuilder result = new System.Text.StringBuilder();
AdomdConnection conn = new AdomdConnection(connectionString);
//Connect to the local serverusing (AdomdConnection conn = new AdomdConnection("Data Source=localhost;"))
{
conn.Open();
//Create a command, using this connection
AdomdCommand cmd = conn.CreateCommand();
cmd.CommandText = #"SELECT { [Measures].[Unit Price] } ON COLUMNS , {[Product].[Color].[Color].MEMBERS-[Product].[Color].[]} * [Product].[Model Name].[Model Name]ON ROWS FROM [Adventure Works] ;";
//Execute the query, returning a cellset
CellSet cs = cmd.ExecuteCellSet();
//Output the column captions from the first axis//Note that this procedure assumes a single member exists per column.
result.Append("\t\t\t");
TupleCollection tuplesOnColumns = cs.Axes[0].Set.Tuples;
foreach (Microsoft.AnalysisServices.AdomdClient.Tuple column in tuplesOnColumns)
{
result.Append(column.Members[0].Caption + "\t");
}
result.AppendLine();
//Output the row captions from the second axis and cell data//Note that this procedure assumes a two-dimensional cellset
TupleCollection tuplesOnRows = cs.Axes[1].Set.Tuples;
for (int row = 0; row < tuplesOnRows.Count; row++)
{
for (int members = 0; members < tuplesOnRows[row].Members.Count; members++ )
{
result.Append(tuplesOnRows[row].Members[members].Caption + "\t");
}
for (int col = 0; col < tuplesOnColumns.Count; col++)
{
result.Append(cs.Cells[col, row].FormattedValue + "\t");
}
result.AppendLine();
}
conn.Close();
TextBox1.Text = result.ToString();
} // using connection
Source : Retrieving Data Using the CellSet
This is fine upto select on columns and on Rows. It will be helpful analyze how to traverse sub select queries from main query.

SQL always returning same results

I'm trying to do a search on a table in my database where it returns the top 50 rows with a firstname like the search term being passed to the function, but its always returning the same 50 results
My sql looks like this:
Select TOP(50) *
FROM [database].[dbo].[records]
WHERE (A_1STNAME LIKE '" + #searchTerm + "%')
ORDER BY A_RECID
When I run this query in Visual Studios query window, it works as expected but when I run it through my ASP.NET application, it always returns the same 50 results, and only one of them has a first name close to the searchTerm I passed to it.
here is the page code that runs the function:
protected void Page_Load(object sender, EventArgs e)
{
_migrated_data data = new _migrated_data();
DataSet ds = data.Search(Request.QueryString.Get("query"), "A_RECID", 50);
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
rpt_Data.DataSource = ds.Tables[0].DefaultView;
rpt_Data.DataBind();
}
}
and here is the search method of _migrated_data:
public DataSet Search(String #pSearchTerm, String #pSortBy, int #pRowCount)
{
DataSet ds = new DataSet();
OleDbConnection objOleDBConn;
OleDbDataAdapter objOleDBDa;
objOleDBConn = new OleDbConnection(ClearingHouse_OLEDDB);
objOleDBConn.Open();
string lSQL = "SELECT TOP(50) * FROM [database].[dbo].[records]";
lSQL += " WHERE (A_1STNAME LIKE #searchTerm ) ORDER BY #sortBy";
SqlCommand t = new SqlCommand(lSQL);
if (pSearchTerm != null && pSearchTerm != "")
{
t.Parameters.AddWithValue("#searchTerm", #pSearchTerm + "%");
}
if (pSortBy != null && pSortBy != "")
{
t.Parameters.AddWithValue("#sortBy", #pSortBy);
}
else
{
t.Parameters.AddWithValue("#sortBy", "A_RECID");
}
objOleDBDa = new OleDbDataAdapter(t.CommandText, objOleDBConn);
objOleDBDa.SelectCommand.CommandType = CommandType.Text;
objOleDBDa.Fill(ds);
objOleDBConn.Close();
return ds;
}
Using locals to view the final CommandText of t, I get the sql results I gave above.
Any help is greatly appriciated :)
AS Rob Rodi said, first of all, to get the results begining with a value you will need % char at the end of the therm:
Select TOP(50) *
FROM [database].[dbo].[records]
WHERE (A_1STNAME LIKE '" + #searchTerm + "%')
ORDER BY A_RECID
Second, probably your searchTerm is empty, so it's grabbing always the same results.
Debug your app and watch the variable to see if it's receiving some value.
You are having SQL injection there. Also it looks like the %-signs are missing.
The fact, that the query works in a query window and not in your app means, that the error is not in your query! Did you think about that? Probably, you should post code of your ASP.NET app.
It sounds like your parameter isn't being correctly passed to your data layer. Easiest way to find out if that's the case is to turn on Sql Profiler and check to see if it's being passed. If it is, your sql's to blame. If it's not, it's your application. You can then use the debugger on your application to work your way up the stack to see where the problem lies.

Lucene.NET & Facete Search Solution

Hey just started using Lucene.NET, any was wondering if anyone had a working example of Lucene.NET with a faceted search.
I know this below link http://www.devatwork.nl/articles/lucenenet/faceted-search-and-drill-down-lucenenet/
Which looked great, but all it does is tell me the number of results in the faceted search but not actually how I can retrieve the index and details of those results. i.e as in a normal search in Lucene.NET.
I.e from that link he has the following snippet
private static void FacetedSearch(string indexPath, string genre, string term){
var searcher = new IndexSearcher(indexPath);
// first get the BitArray result from the genre query
var genreQuery = new TermQuery(new Term("genre", genre));
var genreQueryFilter = new QueryFilter(genreQuery);
BitArray genreBitArray = genreQueryFilter.Bits(searcher.GetIndexReader());
Console.WriteLine("There are " + GetCardinality(genreBitArray) + " document with the genre " + genre);
// Next perform a regular search and get its BitArray result
Query searchQuery = MultiFieldQueryParser.Parse(term, new[] {"title", "description"}, new[] {BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD}, new StandardAnalyzer());
var searchQueryFilter = new QueryFilter(searchQuery);
BitArray searchBitArray = searchQueryFilter.Bits(searcher.GetIndexReader());
Console.WriteLine("There are " + GetCardinality(searchBitArray) + " document containing the term " + term);
// Now do the faceted search magic, combine the two bit arrays using a binary AND operation
BitArray combinedResults = searchBitArray.And(genreBitArray);
Console.WriteLine("There are " + GetCardinality(combinedResults) + " document containing the term " + term + " and which are in the genre " + genre);
}
Which will tell me i.e there is 2 records for the search term "Dublin" and which are in genre "Financial" which is perfect but the article seems to skip the part where it says how I can retrieve the indexes of those results and display on screen.
He does explain this in the link below for a normal search but not facete search..
i.e Normal Search
private static void Search(string indexPath, string term)
{
// create searcher
var searcher = new IndexSearcher(indexPath);
// create a query which searches through the title and description, the term can be in the title or the description
Query searchQuery = MultiFieldQueryParser.Parse(term, new[] {"title", "description"}, new[] {BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD}, new StandardAnalyzer());
// perform the search
Hits hits = searcher.Search(searchQuery);
// loop through all the hits and show their title
for (int hitIndex = 0; hitIndex &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; hits.Length(); hitIndex++)
{
// get the corresponding document
Document hitDocument = hits.Doc(hitIndex);
// write its title to the console
Console.WriteLine(hitDocument.GetField("title").StringValue());
}
}
http://www.devatwork.nl/articles/lucenenet/search-basics-lucenenet/
Any help would be greatly appreciated
Edit :
Or should I do a search query and then do a Filter on the results ?
The BitArray represents hits. Each 1 has an index, that is equal to document id
So 1001001 means that documents with position 0, 3 and 6 in index match your search. You just have to retrieve them from lucene index.
var searcher = new IndexSearcher(indexPath);
// get document at position 0
var doc = searcher.Doc( 0 );

Resources