简体   繁体   中英

Android Filter searchView Widget for scala “ got ClassCastException”

I want to create "searchView widget" for android in Scala plugin eclipse, Here is my code,

 override def getFilter(): Filter = {
  new Filter() {

    protected override def publishResults(constraint: CharSequence, results: 
FilterResults) {
      var books = results.values.asInstanceOf[List[BookMetadata]]
      ItemAdapter.this.notifyDataSetChanged()
    }

    protected override def performFiltering(constraint: CharSequence): FilterResults = {

      val filteredResults = ListBuffer(books.asScala.toList.filter(b =>
        b.toString.startsWith(constraint.toString)): _*) .asInstanceOf[List[BookMetadata]]
      val results = new FilterResults()
      results.values = filteredResults
      results
    }
  }
}

I don't have any error but when I run the program I have this ClassCastException

Here is my Log:

 08-23 13:37:06.986: V/BookFragment(25407): query : modern
 08-23 13:37:06.996: W/Filter(25407): An exception occured during performFiltering()!
 08-23 13:37:06.996: W/Filter(25407): java.lang.ClassCastException:  
scala.collection.mutable.ListBuffer cannot be cast to java.util.List
08-23 13:37:06.996: W/Filter(25407):    at   
com.bitlit.android.BooksFragment$ItemAdapter$$anon$2.
performFiltering(BooksFragment.scala:138)
08-23 13:37:06.996: W/Filter(25407):    at 
android.widget.Filter$RequestHandler.handleMessage(Filter.java:234)

08-23 13:37:06.996: W/Filter(25407):    at   
android.os.Handler.dispatchMessage(Handler.java:99)

 08-23 13:37:06.996: W/Filter(25407): 
at android.os.Looper.loop(Looper.java:137)
08-23 13:37:06.996: W/Filter(25407): 
at android.os.HandlerThread.run(HandlerThread.java:61)

Would you please give me some hints for this implementation

Thanks in advance!

Looking at the trace it seems the line causing issue is this one:

val filteredResults = ListBuffer(books.asScala.toList.filter(b =>
    b.toString.startsWith(constraint.toString)): _*) .asInstanceOf[List[BookMetadata]]

You're doing something like this:

val filteredResults = ListBuffer(meta1, meta2).asInstanceOf[List[BookMetadata]]

So ListBuffer[BookMetadata] is not an instance of List[BookMetadata] . This is the case regardless of if you mean java.util.List or scala immutable List .

You can probably do something like this:

import collection.JavaConverters._
val filteredResults = ListBuffer(/* ... */).asJava
// should return an instance of java.util.List

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM