Raul Figueira Raul Figueira - 12 days ago 5
Android Question

Code works on Android studio emulator but not on my android mobile

When I use the Android Studio Emulator (Nexus 4 API 23) to emulate an app that I made, it works perfectly. But, when I use my cellphone (Samsung SM-G3502T Android 4.3 API 18) to emulate the same app, it gets stuck at this code bellow:

if(activity instanceof CategoriaListaActivity) {
boolean isSelected = (categoriaSelectedId == item.getCodigo());
((CategoriaViewHolder)holder).getNomeTextView().setTextColor(isSelected ? activity.getColor(R.color.colorPrimaryDark) : activity.getColor(R.color.colorAccent));
}


Logcat says:

E/dalvikvm: Could not find class 'android.util.ArrayMap', referenced from method com.android.tools.fd.runtime.Restarter.getActivities
W/dalvikvm: VFY: unable to resolve instanceof 2042 (Landroid/util/ArrayMap;) in Lcom/android/tools/fd/runtime/Restarter;
D/dalvikvm: VFY: replacing opcode 0x20 at 0x006f
I/dalvikvm: Could not find method android.app.Activity.getColor, referenced from method catalog.raulfmiranda.com.catalog.ui.adapter.CategoriaRecyclerAdapter.onBindViewHolder
W/dalvikvm: VFY: unable to resolve virtual method 58: Landroid/app/Activity;.getColor (I)I
D/dalvikvm: VFY: replacing opcode 0x6e at 0x0058
I/dalvikvm: Could not find method android.app.Activity.getColor, referenced from method catalog.raulfmiranda.com.catalog.ui.adapter.CategoriaRecyclerAdapter.onBindViewHolder
W/dalvikvm: VFY: unable to resolve virtual method 58: Landroid/app/Activity;.getColor (I)I
D/dalvikvm: VFY: replacing opcode 0x6e at 0x0067
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41a7a8c8)
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NoSuchMethodError: android.app.Activity.getColor
at catalog.raulfmiranda.com.catalog.ui.adapter.CategoriaRecyclerAdapter.onBindViewHolder(CategoriaRecyclerAdapter.java:52)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5825)


How can I fix it?

Answer

You are calling a method which is available in API >= 23 (documentation), but your mobile only has the deprecated method available (documentation). To solve this, you should use ContextCompat.getColor(Context, int) from the support-v4 library.