java.lang.VerifyError: .../utils/KotlinViewExtKt$animateFadeOut$1
Getting that error while running app on emulator PRE Lolipop (<21 api)
Function causing the trouble:
fun View.animateFadeOut(animDuration: Long = 250) {
this.animate()
.alpha(0F)
.setDuration(animDuration)
.setListener(object : Animator.AnimatorListener {
override fun onAnimationRepeat(p0: Animator?) {}
override fun onAnimationEnd(animation: Animator?, isReverse: Boolean) {
super.onAnimationEnd(animation, isReverse)
show(false)
}
override fun onAnimationEnd(p0: Animator?) {
show(false)
}
override fun onAnimationCancel(p0: Animator?) {
}
override fun onAnimationStart(animation: Animator?, isReverse: Boolean) {
}
override fun onAnimationStart(p0: Animator?) {
}
})
.start()
}
fun View.show(show: Boolean) {
val vis = if (show) View.VISIBLE else View.GONE
if (visibility != vis) {
visibility = vis
}
}
Pointing on .setListener line.
Works perfectly on 21+ api.
AS versio: 3.0.1. Kotlin version: 1.2.21 (tried 1.1.51).
What could be the reason? My bad or kotlin?
Multidex is enabled.
Solution
Based on this issue and this fix:
ViewExtension.kt
fun View.animateFadeOut(animDuration: Long = 250L) {
this.animate()
.alpha(0F)
.setDuration(animDuration)
.setListener(object : AbstractAnimatorListener() {
override fun onAnimationEnd(animation: Animator?, isReverse: Boolean) {
super.onAnimationEnd(animation, isReverse)
show(false)
}
override fun onAnimationEnd(p0: Animator?) {
show(false)
}
})
.start()
}
fun View.show(show: Boolean) {
val vis = if (show) View.VISIBLE else View.GONE
if (visibility != vis) {
visibility = vis
}
}
AbstractAnimatorListener.kt
abstract class AbstractAnimatorListener : Animator.AnimatorListener {
override fun onAnimationRepeat(p0: Animator?) {}
override fun onAnimationEnd(p0: Animator?) {}
override fun onAnimationCancel(p0: Animator?) {}
override fun onAnimationStart(p0: Animator?) {}
override fun onAnimationEnd(animation: Animator?, isReverse: Boolean) {
onAnimationEnd(animation)
}
override fun onAnimationStart(animation: Animator?, isReverse: Boolean) {
onAnimationStart(animation)
}
}
Explanation
Try to remove these methods added in API 26 using Java 8 Defaults and use alternative animation:
Animator.AnimatorListener:
onAnimationEnd added in API level 26
void onAnimationEnd (Animator animation, boolean isReverse)
onAnimationStart added in API level 26
void onAnimationStart (Animator animation, boolean isReverse)
These methods can be overridden, though not required, to get the additional play direction info when an animation starts.
AnimatorSet:
Starting in Android 8.0 (API 26) the AnimatorSet API supports
seeking and playing in reverse.
Note:
/**
* Skipping calling super when overriding this method results in
* {#link #onAnimationStart(Animator)} not getting called.
*/
default void onAnimationStart(Animator animation, boolean isReverse) {
onAnimationStart(animation);
}
I need to add this to my build.gradle file to test it
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
jvmTarget = "1.8"
}
}
or replace
super.onAnimationEnd(animation, isReverse)
by
onAnimationEnd(animation)
to avoid the error:
Super calls to Java default methods are prohibited in JVM target 1.6.
Recompile with '-jvm-target 1.8'
And add the next line to my gradle.properties file thanks to this answer
android.enableD8=true
to avoid the exception:
com.android.dx.cf.code.SimException: default or static interface
method used without --min-sdk-version >= 24
It compiles now, launching a kitKat emulator just now...
It works, and MultiDex is also enabled in my project.
Sorry, I cannot reproduce it.
Alternatively, remove the two methods using Java 8 defaults, it also works.
Note2:
Arpan suggestion about AnimatorListenerAdapter would work but it's not necessary.
You can remove those methods, change the animation and create:
object EmptyAnimatorListener : Animator.AnimatorListener {
override fun onAnimationRepeat(p0: Animator?) {}
override fun onAnimationEnd(p0: Animator?) {}
override fun onAnimationCancel(p0: Animator?) {}
override fun onAnimationStart(p0: Animator?) {}
}
And use delegation like this:
.setListener(object : Animator.AnimatorListener by EmptyAnimatorListener {
override fun onAnimationStart(animation: Animator) {
// Do something
}
override fun onAnimationEnd(animation: Animator) {
// Do something
}
})
Note3:
Reproduced adding it to an extension function:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: ...android, PID: 3409
java.lang.VerifyError: com/.../ui/common/extension/android/view/ViewExtensionKt$animateFadeOut$1
Removing the Api 26 methods using Java Defaults solves the issue.
Replacing the super call calling your onAnimationEnd also solves it:
override fun onAnimationEnd(animation: Animator?, isReverse: Boolean) {
onAnimationEnd(animation)
}
Calling super.onAnimationStart(animation: Animator?, isReverse: Boolean) requires API 26:
Decompiling Kotlin Bytecode shows these methods cannot be resolved:
Related
I have a main activity with a heading and a search field (edit text), I want to be able to search and the results are immediately shown in the fragment, like an onChange instead of waiting for the user to click a button to filter results. (which is in the activity).
I can get it working if I include the Edit Text in my fragment too, but I don't want it that way for design purposes, I'd like to retrieve the user values as they are typed from the activity, and get them in my fragment to filter results
I've tried Bundles but could not get it working, and also not sure If i could use Bundles to get the results as they are being input.
Here's a screenshot to help understand better
You can make it happen using ViewModel + MVVM architecture.
MainActivity:
binding.editText.addTextChangedListener(object: TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable?) {
viewModel.updateSearchText(s)
}
})
ViewModel:
private val _searchText = MutableLiveData<Editable?>()
val searchText: LiveData<Editable?> get() = _searchText
fun updateSearchText(text: Editable?) {
_searchText.value = s
}
Fragment:
searchText.observe(viewLifecycleOwner) {
// TODO: handle the searched query using [it] keyword.
}
If you don't know what View Model is or how to implement it, use the official Google tutorial: https://developer.android.com/codelabs/basic-android-kotlin-training-viewmodel
Another way to achieve this (besides using an Android ViewModel) is use the Fragment Result API.
For instance, if you place the EditText into a fragment (let's call it QueryFragment), you can get the result of the QueryFragment in your SearchResults fragment like so:
// In QueryFragment
editText.addTextChangedListener(object: TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { }
override fun afterTextChanged(s: Editable?) {
setFragmentResult("searchQueryRequestKey", bundleOf("searchQuery" to s.toString()))
}
})
// In SearchResultsFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Retrieve the searched string from QueryFragment
// Use the Kotlin extension in the fragment-ktx artifact
setFragmentResultListener("searchQueryRequestKey") { requestKey, bundle ->
val searchQuery = bundle.getString("searchQuery")
// Perform the search using the searchQuery and display the search results
}
}
My code does not have any runtime error but has the above compile time error I am using
recyclerview
Here is my code
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView.layoutManager= LinearLayoutManager(this)
val items=fetchData()
val adapter=NewsListAdapter(items)
recyclerView.adapter=adapter
}
fun fetchData():ArrayList<String>{
val list=ArrayList<String>()
for (i in 1 until 100){
list.add("Items $i")
}
return list
}
}
NewsListAdapter.kt
class NewsListAdapter(private val items: ArrayList<String>) : RecyclerView.Adapter<NewsViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
val view =LayoutInflater.from(parent.context).inflate(R.layout.items_news,parent,false)
return NewsViewHolder(view)
}
override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
val currentitem=items[position]
holder.titletext.text = currentitem
}
override fun getItemCount(): Int {
return items.size
}
}
class NewsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val titletext: TextView =itemView.findViewById(R.id.textView)
}
This error usually means that previous gradle process didn't finish correctly and is still persists in memory.
For Windows, it helped me to find excessive java processes in the task manager and kill them. They usually hide under your IDE parent process.
For Linux you can do as it says here.
Find these processes with:
ps -ef | grep gradle
and stop them using kill.
Edit
I've created a demo project on Github showing the exact problem. Git Project.
I've written an expandable recyclerView in Kotlin Every row has a play button which uses TextToSpeech. The text of the play button should change to stop whilst its playing, then change back to play when it finishes.
When I call notifyItemChanged within onStart and onDone of setOnUtteranceProgressListener, onBindViewHolder is not called and the rows in the recyclerView will no longer expand and collapse correctly.
t1 = TextToSpeech(context, TextToSpeech.OnInitListener { status ->
if (status != TextToSpeech.ERROR) {
t1?.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
override fun onStart(utteranceId: String?) {
recyclerView.adapter.notifyItemChanged(position)
}
override fun onStop(utteranceId: String?, interrupted: Boolean) {
super.onStop(utteranceId, interrupted)
onDone(utteranceId)
}
override fun onDone(utteranceId: String?) {
val temp = position
position = -1
recyclerView.adapter.notifyItemChanged(temp)
}
override fun onError(utteranceId: String?) {}
// override fun onError(utteranceId: String?, errorCode: Int) {
// super.onError(utteranceId, errorCode)
// }
})
}
})
onBindViewHolder:
override fun onBindViewHolder(holder: RabbanaDuasViewHolder, position: Int){
if (Values.playingPos == position) {
holder.cmdPlay.text = context.getString(R.string.stop_icon)
}
else {
holder.cmdPlay.text = context.getString(R.string.play_icon)
}
}
How can I call notifyItemChanged(position) from within setOnUtteranceProgressListener or what callback can I use so that notifyItemChanged only executes when it's safe to execute?
I tried to replicate your issue and I came to know that it is not working because methods of UtteranceProgressListener is not called on main thread and that's why onBindViewHolder method of the adapter is not called.
This worked for me and should work for you too:
Use runOnUiThread{} method to perform actions on RecyclerView like this:
t1.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
override fun onError(utteranceId: String?) {
}
override fun onStart(utteranceId: String?) {
runOnUiThread {
recyclerView.adapter?.notifyItemChanged(position)
}
}
override fun onStop(utteranceId: String?, interrupted: Boolean) {
super.onStop(utteranceId, interrupted)
onDone(utteranceId)
}
override fun onDone(utteranceId: String?) {
val temp = position
position = -1
runOnUiThread {
recyclerView.adapter?.notifyItemChanged(temp)
}
}
}
I solved the problem using runOnUiThread thanks to Birju Vachhani.
For a full working demo of not just the problem I had, but how to correctly expand and collapse rows in a RecyclerView (no onClick events in onBindViewHolder) see my Gitlab Demo Project.
I am working on an android app where user get points for using the app which can be used to unlock in-app features.
I have a function called rewardPoints() which generates random integer and I want it to get called randomly while the user is using the app. The points then gets added up in database.
fun rewardPoints() {
var points = Random().nextInt((5-1) + 1)
}
How do I call the function rewardPoints() randomly while the user is using/interacting with the app?
I'd use a Handler to post a Runnable that re-posts itself. Like so,
val handler = Handler()
handler.post({
rewardPoints()
handler.postDelayed(this, DELAY_TIME_MS)
})
You could kick this off in your Activity's onResume and stop it onPause to make sure it's only running when the app is active.
You could add an observer on your activities, check whether you have active activities and when that's the case start a periodic task to award points.
Sample:
class MyApp : Application(), Application.ActivityLifecycleCallbacks {
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(this)
}
var count: Int by Delegates.observable(0) { _, old, newValue ->
when (newValue) {
0 -> onBackground()
1 -> if (old == 0) onForeground()
}
}
override fun onActivityResumed(activity: Activity?) {
count++
}
override fun onActivityPaused(activity: Activity?) {
count--
}
fun onForeground() {
Log.d("TAG", "start.")
events.start()
}
fun onBackground() {
Log.d("TAG", "stop.")
events.cancel()
}
val events = object: CountDownTimer(Long.MAX_VALUE, 1000) {
// is called once per second as long as your app is in foreground
override fun onTick(millisUntilFinished: Long) {
if (ThreadLocalRandom.current().nextInt(100) < 5) {
Toast.makeText(this#MyApp, "You earned a point.", Toast.LENGTH_SHORT).show()
}
}
override fun onFinish() { /* will never happen */}
}
/* not needed */
override fun onActivityStarted(activity: Activity?) {}
override fun onActivityDestroyed(activity: Activity?) {}
override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {}
override fun onActivityStopped(activity: Activity?) {}
override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {}
}
If you use architecture components Lifecycle, implementing above is even simpler with https://developer.android.com/reference/android/arch/lifecycle/ProcessLifecycleOwner and listening to the desired Lifecycle.Event
I am using glide and once the image is retrieved it is put into a view, the view is extended and I use the below code in the constructor. The code returns null. Is there a way to wait until it returns the drawable? It works in the listeners and that's why I am asking if there's a way to wait so it can be in the constructors.
Code:
Glide:
Glide
.with(activity).asBitmap()
.load(imageURL)
.into(new SimpleTarget<Bitmap>(currentMap.getWidth(), currentMap.getHeight()) {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
currentMap.setUpMap()
});
}
Drawable in view:
drawable = this.getDrawable();
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.drawable.Drawable.getIntrinsicWidth()' on a null object reference
Use a RequestListener<String, GlideDrawable> that gives you a drawable:
(GlideDrawable is also a Drawable).
Glide.with(activity)
.load("...")
.listener(object : RequestListener<String, GlideDrawable> {
override fun onResourceReady(resource: GlideDrawable?, model: String?, target: Target<GlideDrawable>?, isFromMemoryCache: Boolean, isFirstResource: Boolean): Boolean {
// GlideDrawable extends Drawable :)
}
override fun onException(e: Exception?, model: String?, target: Target<GlideDrawable>?, isFirstResource: Boolean): Boolean = false
})
You will need to remove the asBitmap() call.
My code is kotlin because I copy-pasted it from my project, but I believe you can understand it.