EzDevInfo.com

searchable

A php trait to search laravel models

Getting CakePHP's searchable behavior results to contain deeper associations

I am trying to use CakePHP 1.3.5's searchable behavior with containable behavior to return search results for a specified model and an associated model (Article belongsTo User).

Ignoring the searchable behavior for a moment, the following call to find():

$this->Article->find('all', array(
    'conditions' => array('Article.is_published' => 1),
    'fields' => array('Article.id'),
    'contain' => array('User.name')
));

Executes this SQL query:

SELECT `Article`.`id`, `User`.`name`, `User`.`id` FROM `articles` AS `Article` LEFT JOIN `users` AS `User` ON (`Article`.`user_id` = `User`.`id`) WHERE `Article`.`is_published` = 1 

And returns the following array:

Array (
    [0] => Array (
        [Article] => Array (
            [id] => 10
        )
        [User] => Array (
            [name] => Author Name
            [id] => 7
        )
    )
    ...
)

Which is exactly what's expected. However, the following call to search():

$this->Article->search($query, array(
    'conditions' => array('Article.is_published' => 1),
    'fields' => array('Article.id'),
    'contain' => array('Article' => array('User.name'))
));

Executes this SQL query:

SELECT `Article`.`id` FROM `search_index` AS `SearchIndex` LEFT JOIN `articles` AS `Article` ON (`SearchIndex`.`model` = 'Article' AND `SearchIndex`.`association_key` = `Article`.`id`) WHERE `Article`.`is_published` = 1 AND MATCH(`SearchIndex`.`data`) AGAINST('search term' IN BOOLEAN MODE) AND `Article`.`id` IS NOT NULL 

And returns this array:

Array (
    [0] => Array (
        [Article] => Array (
            [id] => 9
        )
    )
    ...
)

Looking at the search() method, it is returning $this->SearchIndex->find('all', $findOptions);. $findOptions contains the following:

Array (
    [conditions] => Array (
        [Article.is_published] => 1
        [0] => MATCH(SearchIndex.data) AGAINST('search term' IN BOOLEAN MODE)
    )
    [fields] => Array (
        [0] => Article.id
    )
    [contain] => Array (
        [Article] => Array (
            [0] => User.name
        )
    )
)

The association isn't getting lost along the way, because inside SearchableBehavior, $this->SearchIndex->Article->belongsTo['User'] is present and intact immediately before and after the call to find() inside the search() method.

The call to search() returns the exact same thing for all of the following values of 'contain':

array('Article' => array('User.name'))

array('Article' => array('User'))

array('Article' => array('User' => array()))

array('Article' => array('User' => array('fields' => array('User.name'))))

array('Article' => array('User' => array('fields' => array('name'))))

Am I doing something wrong? I think I'm using the same format as is instructed in the CakePHP documentation, and I haven't found anything online that suggests that you have to do something special to get search results with associated data.

I know that I could easily achieve the result that I want by just looking up the Users with additional calls to find(), but I'd like to get containable behavior to work like it's supposed to and cut down on unnecessary extra database queries.


Source: (StackOverflow)

Android: SearchableInfo is null when using packageNameSuffix in Gradle build script

I encountered that the method getSearchableInfo always returns null during SearchView initialization if I use the packageNameSuffix in the project's Gradle build script.

SearchView initialization:

final SearchManager searchManager = (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
SearchableInfo info = searchManager.getSearchableInfo(componentName);
mSearchView.setSearchableInfo(info);

Project's build.gradle:

android {
    [...]
    buildTypes {
        debug {
            packageNameSuffix ".debug"
            versionNameSuffix "-debug"
            signingConfig signingConfigs.debug
        }
        [...]
    }
}

If the package suffix is not used, the given componentName is ComponentInfo{com.example.android/com.example.android.MapActivity} and the SearchView as well as its associated SuggestionsProvider work fine.

But if packageNameSuffix is set to ".debug", the given componentName is ComponentInfo{com.example.android.debug/com.example.android.MapActivity} and the SearchManager returns null, instead of returning the respective SearchableInfo object.

Does anyone know how to get the right SearchableInfo from the SearchManager? Thanks!

[EDIT]

Eugen Martinov mentioned in the comments that this behaviur could have to do something with an improper or missing authorities renaming. But i also configured a build type dependent naming of the authorities, that i omitted in the initial post for the sake of simplicity.

Project's build.gradle:

android {
    [...]
    sourceSets {
        debug {
            java.srcDirs = [
                'src/main/java'
            ]
            java.srcDirs = [
                'src/debug/res',
                'src/main/res'
            ]
        }
        release {
            java.srcDirs = [
                'src/main/java'
            ]
            java.srcDirs = [
                'src/release/res',
                'src/main/res'
            ]
        }
        [...]
    }
}

src/debug/res/values/build-config.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="cfg_app_name">App - Debug</string>
    <string name="cfg_authorities">com.example.debug.SuggestionsProvider</string>
    <string name="cfg_maps_key"><!-- some key --></string>
</resources>

src/release/res/values/build-config.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="cfg_app_name">App</string>
    <string name="cfg_authorities">com.example.SuggestionsProvider</string>
    <string name="cfg_maps_key"><!-- some other key --></string>
</resources>

src/main/res/xml/searchable.xml:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:hint="@string/action_search_hint"
    android:label="@string/cfg_app_name"
    android:includeInGlobalSearch="false"
    android:queryAfterZeroResults="true"
    android:searchSuggestAuthority="@string/cfg_authorities"
    android:searchSuggestIntentAction="android.intent.action.VIEW"
    android:searchSuggestThreshold="3" />

Installing both the debug (with the packageNameSuffix option) and the release apk on the same device works. I don't get an error like Failure [INSTALL_FAILED_CONFLICTING_PROVIDER]... But as already said, SearchableInfo is null then.

Installing both apk withouth the packageNameSuffix option leads into the following error: Failure [INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES] - Installation failed since the device already has an application with the same package but a different signature.

Or am i missing something here?

[/EDIT]


Source: (StackOverflow)

Advertisements

Grails - Searchable plugin: Cannot search data in a one to many relationship

Sorry if the title is not that specific, but I don't know how else to state my problem. I'm using the searchable plugin and everything was fine until I needed to search for information that is on a domain associated by a hasMany - BelongsTo.
Example:
I have two classes:

class Author {
  String name
  static hasMany = [books: Book]
  static searchable = true
}

And

class Book {
  String name
  static belongTo = [author: Author]
  static searchable = true
}

I need to be able to search a book given either it's name or author.
But when calling Book.search(query, [properties:['name', author]]) just the name of the Book is searched, but never the Author.
I have tried with author component: true(on Book class), root:false (on Author class) with no luck.

This issue already costed me hours, and I was sure it had to be something simple to implement.


Source: (StackOverflow)

Grails Searchable Plugin - No entities listed to be indexed

I am using the Searchable Plugin 0.6.4 in a Grails 2.2.3 application, but I am encountering a strange error. The error says: GrailsContextLoader Error initializing the application: No entities listed to be indexed, have you defined your entities correctly?

I only have one class listed to be indexed. Below is that class (simplified a bit):

class Incident {

    String howReceived
    Date timeOfCall
    Date timeOfArrival

    User reportingOfficer

    static searchable = [ except: ['version', 'dateCreated', 'lastUpdated'] ]

    static embedded = [ 'witnesses' ]
    static hasMany = [ witnesses: Witness ]

    static mapping = {
        datasource 'police'
        table 'incidents'
    }
}

That's all I have, a simple mapping. Below I've also included my stack trace and debug statements I turned on.

Edit: It appears that for some reason the sessionFactory bean is not finding any class meta data in the DefaultHibernateEntitiesLocator class. So...

Map allClassMetaData = sessionFactory.getAllClassMetadata();
assert allClassMetaData == null

Not sure why or if that information helps.

Debugging

searchable.SearchableGrailsPlugin Not found: Searchable
searchable.SearchableGrailsPlugin Trying to load config from 'SearchableConfiguration.class'
searchable.SearchableGrailsPlugin Not found: SearchableConfiguration
searchable.SearchableGrailsPlugin Defining Compass and Compass::GPS beans
searchable.SearchableGrailsPlugin Done defining Compass and Compass::GPS beans
spring.DefaultSearchableCompassFactoryBean Building SearchableCompassFactoryBean with grailsApplication [org.codehaus.groovy.grails.commons.DefaultGrailsApplication@10fdea05] and compassClassMappingXmlBuilder [grails.plugin.searchable.internal.compass.mapping.DefaultSearchableCompassClassMappingXmlBuilder@e0ef6fa]
spring.SearchableCompassFactoryBean Building new Compass
config.EnvironmentSearchableCompassConfigurator Setting Compass connection to [/Users/grantmcconnaughey/.grails/projects/campus-police/searchable-index/development]
config.DefaultGrailsDomainClassMappingSearchableCompassConfigurator Mapping class [com.company.police.Incident] with strategy [searchable class property]
config.DefaultGrailsDomainClassMappingSearchableCompassConfigurator No mapping strategy found for class [com.company.police.Employee]: assuming this class is not searchable
mapping.SearchableGrailsDomainClassCompassMappingUtils Mapping [Incident.howReceived]
mapping.SearchableGrailsDomainClassCompassMappingUtils Mapping [Incident.id]
mapping.SearchableGrailsDomainClassCompassMappingUtils Mapping [Incident.timeOfArrival]
mapping.SearchableGrailsDomainClassCompassMappingUtils Mapping [Incident.timeOfCall]
mapping.DefaultSearchableCompassClassMappingXmlBuilder Building Compass mapping XML for [com.company.police.Incident] from description [CompassClassMapping: mappedClass=[class com.company.police.Incident],  mappedClassSuperClass=[null], alias=[Incident], spellCheck=[null], subIndex=[null], root=[true], poly=[false], extend=[null], propertyMappings=[[CompassClassPropertyMapping: type=[property], propertyName=[domestic], attributes=[{}], CompassClassPropertyMapping: type=[property], propertyName=[hateCrime], attributes=[{}], CompassClassPropertyMapping: type=[property], propertyName=[howReceived], attributes=[{}], CompassClassPropertyMapping: type=[id], propertyName=[id], attributes=[{}], CompassClassPropertyMapping: type=[property], propertyName=[occurredFrom], attributes=[{}], CompassClassPropertyMapping: type=[property], propertyName=[occurredTo], attributes=[{}], CompassClassPropertyMapping: type=[property], propertyName=[officerAssaulted], attributes=[{}], CompassClassPropertyMapping: type=[property], propertyName=[officerKilled], attributes=[{}], CompassClassPropertyMapping: type=[property], propertyName=[readyForSignature], attributes=[{}], CompassClassPropertyMapping: type=[property], propertyName=[reportNumber], attributes=[{}], CompassClassPropertyMapping: type=[property], propertyName=[timeOfArrival], attributes=[{}], CompassClassPropertyMapping: type=[property], propertyName=[timeOfCall], attributes=[{}]]]]
mapping.DefaultSearchableCompassClassMappingXmlBuilder Mapping Searchable Property 'com.company.police.Incident.howReceived' with property attributes [name:howReceived] and meta-data [howReceived:[:]]
mapping.DefaultSearchableCompassClassMappingXmlBuilder Mapping Searchable Property 'com.company.police.Incident.timeOfArrival' with property attributes [name:timeOfArrival] and meta-data [timeOfArrival:[:]]
mapping.DefaultSearchableCompassClassMappingXmlBuilder Mapping Searchable Property 'com.company.police.Incident.timeOfCall' with property attributes [name:timeOfCall] and meta-data [timeOfCall:[:]]
mapping.DefaultSearchableCompassClassMappingXmlBuilder com.company.police.Incident xml [<?xml version="1.0"?>
<!DOCTYPE compass-core-mapping PUBLIC 
    "-//Compass/Compass Core Mapping DTD 2.0//EN"
    "http://www.compass-project.org/dtd/compass-core-mapping-2.2.dtd">
<compass-core-mapping>
  <class name='com.company.police.Incident' alias='Incident' root='true' poly='false' support-unmarshall='true'>
    <id name='id' />
    <property name='howReceived'>
      <meta-data>howReceived</meta-data>
    </property>
    <property name='timeOfArrival'>
      <meta-data>timeOfArrival</meta-data>
    </property>
    <property name='timeOfCall'>
      <meta-data>timeOfCall</meta-data>
    </property>
  </class>
</compass-core-mapping>]
mapping.SearchableClassPropertySearchableGrailsDomainClassMappingConfigurator Adding [com.company.police.Incident] mapping to CompassConfiguration
spring.SearchableCompassFactoryBean Done building Compass
domain.DynamicDomainMethodUtils Adding searchable methods to [com.company.police.Incident]
searchable.SearchableGrailsPlugin Started Compass::GPS
compass.CompassGpsUtils Starting Searchable Plugin bulk index

Stacktrace

context.GrailsContextLoader Error initializing the application: No entities listed to be indexed, have you defined your entities correctly?
java.lang.IllegalArgumentException: No entities listed to be indexed, have you defined your entities correctly?
    at org.compass.gps.device.support.parallel.ConcurrentParallelIndexExecutor.performIndex(ConcurrentParallelIndexExecutor.java:88)
    at org.compass.gps.device.support.parallel.AbstractParallelGpsDevice.index(AbstractParallelGpsDevice.java:119)
    at org.compass.gps.impl.DefaultReplaceIndexCallback.buildIndexIfNeeded(DefaultReplaceIndexCallback.java:42)
    at org.compass.core.lucene.engine.manager.DefaultLuceneSearchEngineIndexManager$ReplaceIndexOperationCallback.firstStep(DefaultLuceneSearchEngineIndexManager.java:281)
    at org.compass.core.lucene.engine.manager.DefaultLuceneSearchEngineIndexManager.doOperate(DefaultLuceneSearchEngineIndexManager.java:218)
    at org.compass.core.lucene.engine.manager.DefaultLuceneSearchEngineIndexManager.doReplaceIndex(DefaultLuceneSearchEngineIndexManager.java:266)
    at org.compass.core.lucene.engine.manager.DefaultLuceneSearchEngineIndexManager.replaceIndex(DefaultLuceneSearchEngineIndexManager.java:261)
    at org.compass.gps.impl.SingleCompassGps.doIndex(SingleCompassGps.java:118)
    at org.compass.gps.impl.AbstractCompassGps.index(AbstractCompassGps.java:154)
    at org.compass.gps.impl.AbstractCompassGps.index(AbstractCompassGps.java:128)
    at grails.plugin.searchable.internal.compass.CompassGpsUtils.index(CompassGpsUtils.java:49)

Source: (StackOverflow)

Grails searchable relationship

I am wondering how to return specific domain with searchable? For example we have domain A and B. Both domain are searchable and have relationship: A has many B and B belongs to A. Another case A and B have many-to-many relationship.

Now when I search for item, I must always return A item. In my case let say I found matches in B, I need to return all As for each B. Other way around should work as well.

Currently I do a search query is searchable services:

def searchResults = searchableService.search(params.q, params)

Is there a way to get all related A domain for any search results?

Thank you.


Source: (StackOverflow)

Grails 2.4.4 + searchable:0.6.9 runtime issues

When trying to add the searchable:0.6.9 (or lesser ones) on a Grails 2.4.4 app I get an exception thrown by hibernate4, but this only happens when I add the "static searchable = true" to my domain class.

Considering that my BuildConfig.groovy looks like this:

repositories {
    inherits true // Whether to inherit repository definitions from plugins

    grailsPlugins()
    grailsHome()
    mavenLocal()
    grailsCentral()
    mavenCentral()

    mavenRepo "https://repo.grails.org/grails/core"
    mavenRepo "https://oss.sonatype.org/content/repositories/releases/"
    mavenRepo "http://repo.spring.io/milestone"

}

dependencies {

    compile "org.compass-project:compass:2.2.1"
    compile('org.apache.lucene:lucene-highlighter:4.10.2',
              'org.apache.lucene:lucene-spellchecker:3.6.2')

    test "org.grails:grails-datastore-test-support:1.0.2-grails-2.4"
    compile "javax.validation:validation-api:1.1.0.Final"
    runtime "org.hibernate:hibernate-validator:5.0.3.Final"
}

plugins {
    // plugins for the build system only
    build ":tomcat:7.0.55"

    // plugins for the compile step
    compile ":scaffolding:2.1.2"
    compile ':cache:1.1.8'
    compile ":asset-pipeline:1.9.9"

    runtime ":hibernate4:4.3.6.1" // or ":hibernate:3.6.10.18"
    runtime ":database-migration:1.4.0"
    runtime ":jquery:1.11.1"
    runtime ":searchable:0.6.9"
}

I get this exception:

ERROR context.GrailsContextLoaderListener - Error initializing the application: org/hibernate/impl/SessionFactoryImpl Message: org/hibernate/impl/SessionFactoryImpl Line | Method ->> 95 | injectLifecycle in org.compass.gps.device.hibernate.lifecycle.DefaultHibernateEntityLifecycleInjector 147 doStart in org.compass.gps.device.hibernate.HibernateGpsDevice

Does someone know how to make things work please?


Source: (StackOverflow)

What text processing tool is recommended for parsing screenplays?

I have some plain-text kinda-structured screenplays, formatted like the example at the end of this post. I would like to parse each into some format where:

  • It will be easy to pull up just stage directions that deal with a specific place.
  • It will be easy to pull up just dialogue belonging to a particular character.

The most obvious approach I can think of is using sed or perl or php to put div tags around each block, with classes representing character, location, and whether it's stage directions or dialogue. Then, open it up as a web-page and use jQuery to pull out whatever I'm interested in. But this sounds like a roundabout way to do it and maybe it only seems like a good idea because these are tools I'm accustomed to. But I'm sure this is a recurring problem that's been solved before, so can anybody recommend a more efficient workflow that can be used on a Linux box? Thanks.

Here is some sample input:

      SOMEWHERE CORPORATION - OPTIONAL COMMENT
      A guy named BOB is sitting at his computer.

                             BOB
                Mmmm. Stackoverflow. I like.

      Footsteps are heard approaching.

                             ALICE
                Where's that report you said you'd have for me?

      Closeup of clock ticking.

                             BOB (looking up)
                Huh? What?

                             ALICE
                Some more dialogue.

      Some more stage directions.

Here is what sample output might look like:

      <div class='scene somewhere_corporation'>
       <div class='comment'>OPTIONAL COMMENT</div>
       <div class='direction'>A guy named BOB is sitting at his computer.</div>
       <div class='dialogue bob'>Mmmm. Stackoverflow. I like.</div>
       <div class='direction'>Footsteps are heard approaching.</div>
       <div class='dialogue alice'>Where's that report you said you'd have for me?</div>
       <div class='direction'>Closeup of clock ticking.</div>
       <div class='comment bob'>looking up</div>
       <div class='dialogue bob'>Huh? What?</div>
       <div class='dialogue alice'>Some more dialogue.</div>
       <div class='direction'>Some more stage directions.</div>
      </div>

I'm using DOM as an example, but again, only because that's something I understand. I'm open to whatever is considered a best practice for this type of text-processing task if, as I suspect, roll-your-own regexps and jQuery is not the best practice. Thanks.


Source: (StackOverflow)

is there any opensource solution for creating searchable pdf on windows?

I am searching an all-in-one solution to create searchable PDF files (via OCR) from image-only PDF files (scanned documents) in a single step (e.g. calling a command line from another program)

I found some software bundles:

  • pdfsandwich (its hard to port on windows systems)
  • watchOCR (discontinued :-( )

I played around whit tesseract, but it only supports single TIFF images as input and then I have to combine the OCR result with image, bind all combined pages to a new PDF document.

I am writing a Java based program so inspect PDF files and if necessary it should convert them into searchable pdfs (pdf with a text layer, recognized images via OCR)

It would be really great if there is any idea how I could simplify all these single steps and use Tesseract for the following workflow:

PDF with scanned Images =====> input (processing) output ====> recognized PDF with searchable Text

Thanks very much in advance

best regards

Shannon


Source: (StackOverflow)

How do I map Grails Searchable plugin across more than 2 domain objects?

I'm using the Searchable plugin in my Grails application, but am having trouble getting it to map across more than 2 domain objects while returning valid search results. I've looked through the Searchable plugin documentation, but cannot find the answer to my question. Here's a very basic example of the domains I have:

class Article {

     static hasMany = [tags: ArticleTag]

     String title
     String body
}

class ArticleTag {
     Article article
     Tag tag
}

class Tag {
     String name
}

Ultimately what I'm looking to do is be able to find articles by searching their titles, body and associated tags. The titles and tags would be boosted as well.

What's the proper way to map these classes to meet the desired results?


Source: (StackOverflow)

How to end old Activity when Search starts new Activity

I have an application that presents a sort of catalog of items in a ListView. The list is rather long, so I've implemented the Search capability like this:

    <activity android:name=".ItemsOverview"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <!-- enable the search dialog to send searches to ItemsSearch -->
        <meta-data android:name="android.app.default_searchable"
                   android:value=".ItemsSearch" />
    </activity>
...
...
    <activity android:name=".ItemsSearch">
        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>
        <meta-data android:name="android.app.searchable"
                   android:resource="@xml/searchable" />
    </activity>

ItemsSearch then presents the same ListView, but containing only items that match the Search criteria.

There are two fundamental problems with this:

  1. ItemsSearch is an almost duplicate of ItemsOverview (but with some enhancements for the search capability);
  2. ItemsSearch overlays ItemsOverview such that if three or four searches are done, it takes four or five presses of the Back button to get out. Not quite the desired effect. :)

I would like to, in some fashion, end the original Activity when the second Activity starts and, ideally, combine the two Classes (Overview and Search) into one. Is there a way for my Activity to detect that it's already running in another process, and to kill that other process at inception?

Once I understand this, I can probably figure out how to combine the two. What do others do when they need to utilize a filtered list?


Source: (StackOverflow)

set numeric input type to SearchView in ActionBar

I don't manage to set the numeric input type to the SearchView in my ActionBar. I have the following searchable.xml file in my res/xml folder:

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:inputType="number"
    android:label="@string/app_name"
    android:hint="@string/search_hint">
</searchable>  

And I set the searchable configuration to the SearchView as follows:

 // Get the SearchView and set the searchable configuration
 SearchManager searchManager = (SearchManager)    getSystemService(Context.SEARCH_SERVICE);
 SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
 searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

The search_hint is set correctly, but the line android:inputType="number" seems to have no effect, i.e. the numeric keypad doesn't appear.

Does anyone have a solution for this?


Source: (StackOverflow)

Grails 2.4 + Hibernate 4 + Searchable plugin = ClassNotFoundException: org.hibernate.impl.SessionFactoryImpl

Recently I was integrating a simple Grails application with the Searchable plugin. What I've found was that Searchable plugin does not work with Hibernate 4 library.

Here you can find a sample application that contains only clean Grails 2.4 app with only Searchable plugin added - https://github.com/wololock/grails-searchable-example

When I run this app with:

runtime ":hibernate4:4.3.5.5"

dependency, it wont start and throws an exception:

ClassNotFoundException: org.hibernate.impl.SessionFactoryImpl

What I have found already is that in the Hibernate4 SessionFactoryImpl was moved to the org.hibernate.internal package and it seems like Compass looks for this class in the old location:

2014-10-11 19:41:58,142 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener  - Error initializing the application: org/hibernate/impl/SessionFactoryImpl
Message: org/hibernate/impl/SessionFactoryImpl
Line | Method
->>   95 | injectLifecycle in org.compass.gps.device.hibernate.lifecycle.DefaultHibernateEntityLifecycleInjector

Switching back to the:

runtime ":hibernate:3.6.10.17"

and changing

cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'

in the DataSource.groovy resolves the problem.

My question is: is there any workaround to use Searchable plugin with Hibernate 4 or we have to wait or fix the issue in Compass/Searchable source code? How did you deal with that problem in your Grails application? I will be grateful for your tips.


Source: (StackOverflow)

Android abs with SearchView, onQueryTextListener not working

I'm trying to use the SearchView Support v4 version with action bar sherlock.

So i have my search button in the action bar -> when i touch it the keyboard show up and the searchBar too.

My problem is that i need to use the listeners onQueryTextSubmit and onQueryTextChange but they are never fired. I need to use the searh query string and do custom stuff with it.

Here is the full activity.java

public class ActivityMain extends SherlockFragmentActivity implements OnQueryTextListener, DialogFragmentListener {
    /**
     * PRIVATE ATTRIBUTES
     */
    private static final String TAG                             = "ActivityMain";
    private ViewPager           _viewPager;
    private TabsAdapter         _tabsAdapter;
    private DialogFiltre        _dialogFiltre;
    private String              _searchCurrentQuery;
    // data
    private boolean             _doubleBackToExitPressedOnce    = false;


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        menu.clear();
        switch ((int) _viewPager.getCurrentItem()) {
            case 0:
                getSupportMenuInflater().inflate(R.menu.empty_menu, menu);
                break;
            case 1:
                getSupportMenuInflater().inflate(R.menu.action_bar_menu, menu);
                break;
            case 2:
                getSupportMenuInflater().inflate(R.menu.empty_menu, menu);
                break;
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getSupportMenuInflater().inflate(R.menu.action_bar_menu, menu);
        MenuItem searchItem = menu.findItem(R.id.search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setSubmitButtonEnabled(true);
        searchView.setOnQueryTextListener(queryTextListener);
        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {

        Log.i(TAG, "onQueryTextSubmit--");
        onSearchClicked(query);
        // hide keyboard
        InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {

        Log.d(TAG, "onQueryTextChange--");
        _searchCurrentQuery = newText.toString();
        EtablissementApplication._adapter.getFilter().filter(_searchCurrentQuery);
        return true;
    }

    private void onSearchClicked(String query) {

        Log.d(TAG, "onSearchClicked--");
        _searchCurrentQuery = query.toString();
        EtablissementApplication._adapter.getFilter().filter(_searchCurrentQuery);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                break;
            case R.id.search:
                break;
            case R.id.menu_filtre:
                _dialogFiltre = DialogFiltre.newInstance(R.string.menu_filtre, this);
                _dialogFiltre.setValidDialogListener(this);
                _dialogFiltre.show(getSupportFragmentManager(), null);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

Source: (StackOverflow)

How to pass database adapter to another activity?

I'm having some trouble understanding the search dialog in the Android SDK.

The "main activity" of my application provides a button. If the user clicks this button the search dialog is called. The search itself is then done in an async task as it might need some time. So far so good.

The main activity also creates a database adapter object which is used to initialize the database, perform queries, etc. But how can I use this adapter object in the searchable activity?

MAIN activity
// Init database
DatabaseAdapter dba = new DatabaseAdapter();
dba.init();
// open search dialog
if (buttonClick) onSearchRequest();

Searchable activity

  1. Get intent and receive query from search dialog -> OK
  2. How can I use the database adapter again to perform a query?

Do I have to create a new object? Can I pass it somehow from the min activity to the searchable activity, [...]?

Thanks,
Robert


Source: (StackOverflow)

Variable search hint

In my searchable.xml in my android project, I get to specify a hint that appears in the edittext, when no text is written. Is there any way to dynamically set this?

In my action, I have two search buttons, that are calling startSearch passing their own parameters. I would like to set hints that reflect the selected action, based on which button was clicked - say "search movie titles", "search actors".

The way I see it, this could potentially be achievable by passing parameters to startSearch, or using a localization approach, just as I could place one hint in values-fr\strings.xml, there might be an alternative search resource file to target for when another button has been clicked? Or if the searchable.xml could be made into a selector, so that I could have it act differently in different states, somehow, that would also be fine... Problem is I haven't been able to find a means of achieving any of these.

The real reason I want to be doing this, is because the way I see it, it's the best way of communicating that the default action, when the device search button is pressed, is the first option, title search.

UPDATE

To avoid confusion, I'm happy with any declarative or programmatic approach of changing the hint in the EditText mSearchTextField in SearchDialog. What I'm unclear about is how to reference that EditText. The comments in the code linked to says "This is still controlled by the SearchManager ..." but I can't find any reference to how it can be controlled from the SearchManager either.


Source: (StackOverflow)