IndexOutOfBoundsException for EditText setSelection Android - android

The Fragments crashes when trying to get the data using the location with the error below:
2022-05-26 00:42:46.057 30678-30678/com.example.android.politicalpreparedness E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.politicalpreparedness, PID: 30678
java.lang.IndexOutOfBoundsException: setSpan (5 ... 5) ends beyond length 0
at android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1325)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:684)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:676)
at android.text.Selection.setSelection(Selection.java:96)
at android.text.Selection.setSelection(Selection.java:78)
at android.widget.EditText.setSelection(EditText.java:129)
at com.example.android.politicalpreparedness.representative.RepresentativeFragment$populateStatesInformation$1.onChanged(RepresentativeFragment.kt:119)
at com.example.android.politicalpreparedness.representative.RepresentativeFragment$populateStatesInformation$1.onChanged(RepresentativeFragment.kt:23)
at androidx.lifecycle.LiveData.considerNotify(LiveData.java:131)
at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:149)
at androidx.lifecycle.LiveData.setValue(LiveData.java:307)
at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:50)
at androidx.lifecycle.LiveData$1.run(LiveData.java:91)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
I am confused how this is causing an error. It's supposed to show the value that's in the adapter right?
Fragment Code :
private fun populateStatesInformation() {
val statesArray = requireContext().resources.getStringArray(R.array.states)
binding.addressState.setAdapter(ArrayAdapter(requireContext(), R.layout.layout_state_list_item, statesArray))
viewModel.address.observe(viewLifecycleOwner) {
var index = statesArray.indexOf(it.state)
if (index == -1) {
index = 0
}
binding.addressState.setSelection(index)
}
}
The XML Code for that text field.
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/address_state_layout"
style="#style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:hint="#string/address_state"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#id/address_zip_layout"
app:layout_constraintTop_toTopOf="#id/address_zip_layout">
<AutoCompleteTextView
android:id="#+id/address_state"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:editable="false"
android:ellipsize="end"
android:maxLines="1"
tools:ignore="Deprecated,LabelFor" />
</com.google.android.material.textfield.TextInputLayout>

This error is because setSelection(i) doesn't select item i from the adapter for a AutoCompleteTextView, it attempts to move the cursor to position i in the current text, so if i is greater than the length of the text you get that error.
You can use setSelection(i) with a Spinner, but it has different behavior with an AutoCompleteTextView. To do the equivalent of setSelection in a AutoCompleteTextView, use this instead of the setSelection call:
binding.addressState.setText(statesArray[index], false)
The second argument (false) is necessary for it to operate like a spinner and keep the options around instead of applying a filter.
There is an older, but still useful, thread about this issue here too.

Related

Unable to get button background color

I am trying to obtain the current background color of a button from a randomized color palette. However, my app is always crashing when I try the following code.
int activeColor = ((ColorDrawable)color1.getBackground()).getColor();
I always get this error message.
Process: com.boredgiant.chora, PID: 17418
java.lang.ClassCastException: android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable
at com.boredgiant.chora.DrawActivity$103.onClick(DrawActivity.java:850)
at android.view.View.performClick(View.java:6314)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View$PerformClick.run(View.java:24793)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6543)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
You need to cast it to RippleDrawable
int activeColor = ((RippleDrawable)color1.getBackground()).getColorStateList().getDefaultColor();

java.lang.ClassCastException on CardView only when SearchView is present in layout

I have a problem regarding android layout that I am not able to resolve. I have a fragment with a layout that contains lots of elements and in particular this CardView element
<androidx.cardview.widget.CardView
android:id="#+id/search_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
app:cardBackgroundColor="#color/chartMax"
app:cardCornerRadius="20dp"
app:cardElevation="2dp">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:text="Cerca"
android:textAlignment="center"
android:textColor="#fff"
android:textSize="23sp" />
</androidx.cardview.widget.CardView>
I access this element in fragment
private lateinit var searchButton: CardView
searchButton = view.search_button
and everything works fine, I can use it normally.
The problems start when I add a normal SearchView to the fragment.
<androidx.appcompat.widget.SearchView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
When I run the application it crash on this instruction
searchButton = view.search_button
This is the stacktrace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: io.atoka.mobile, PID: 31291
java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageView cannot be cast to androidx.cardview.widget.CardView
at io.atoka.mobile.fragments.SearchFragment.getViewElements(SearchFragment.kt:57)
at io.atoka.mobile.fragments.SearchFragment.onCreateView(SearchFragment.kt:73)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3273)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3229)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:620)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1391)
at android.app.Activity.performStart(Activity.java:7157)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:2937)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
like if my CardView was an AppCompatImageView that is not. When I remove the SearchView the application works normally.
Anyone knows the solution? Is there any bug regarding this particular case?
Thank you
Your problem occurs because of the name you gave to your cardview
search_button is already define in default androidx.appcompat.widget.SearchView class as below:
final ImageView mSearchButton;
mSearchButton = findViewById(R.id.search_button);
so when you trying to get it from binding it's getting conflicted with the SearchView class search_button parameter
try to change the name of your cardview to something else then try,

Why does the application crash when trying to select text?

When I try to select text many times in the TextView, the application crashes with the error.
Does anyone know what could be the problem?
Error Stacktrace:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: *** PID: 11481
java.lang.IndexOutOfBoundsException: setSpan (-1 ... -1) starts before 0
at android.text.SpannableStringInternal.checkRange(SpannableStringInternal.java:442)
at android.text.SpannableStringInternal.setSpan(SpannableStringInternal.java:163)
at android.text.SpannableStringInternal.setSpan(SpannableStringInternal.java:152)
at android.text.SpannableString.setSpan(SpannableString.java:46)
at android.text.Selection.setSelection(Selection.java:76)
at android.widget.Editor$SelectionModifierCursorController.resetDragAcceleratorState(Editor.java:5790)
at android.widget.Editor$SelectionModifierCursorController.onTouchEvent(Editor.java:5627)
at android.widget.Editor.onTouchEvent(Editor.java:1416)
at android.widget.TextView.onTouchEvent(TextView.java:9922)
at android.view.View.dispatchTouchEvent(View.java:11843)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2981)
....
2019-07-28 16:00:53.369 11481-11481/? E/AndroidRuntime: at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4650)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4623)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7222)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7196)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:7157)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7379)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:193)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:379)
at android.os.Looper.loop(Looper.java:144)
at android.app.ActivityThread.main(ActivityThread.java:7383)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)
Here is the markup for TextView:
<TextView
android:id="#+id/list_item_message_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:layout_marginBottom="6dp"
android:gravity="center_vertical"
android:inputType="none"
android:linksClickable="true"
android:singleLine="false"
android:text="TextView"
android:lineSpacingExtra="3dp"
android:textIsSelectable="true"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent" />
In the code I set the attribute: messageView.setMovementMethod (LinkMovementMethod.getInstance ());
I was able to reproduce only on android O and android N, in the following scenario:
Given a RecyclerView which presents a ViewHolder containing a TextView
That TextView as .setTextIsSelectable(true) and .setMovementMethod(LinkMovementMethod.getInstance())
Selecting a text from TextView and scrolling away from that particular view will cause crash. In particular, scrolling away while having presented that system overlay which offers "Copy", "Cut", "Paste", etc
So, my workaround (not a real solution but it will prevent crashes and it doesn't take users out of my app) was not allowing text selection on affected builds:
val selectable = when {
Build.VERSION.SDK_INT <= Build.VERSION_CODES.M -> true
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P -> true
else -> false
}
textView.setTextIsSelectable(selectable)
textView.setMovementMethod(LinkMovementMethod.getInstance())
remove this
android:lineSpacingExtra="3dp"
Try to specify android:inputType="text". As well, you can add android:autoLink="all"
I think this is a problem in the Android Framework. Similar to the one described here:
java.lang.IndexOutOfBoundsException: getChars (7 ... 0) has end before start
Because and I have a similar error too. Thank you all.

App crashes when I press the textview

I have the following TextView
<TextView
android:id="#+id/LoginlinkLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical center_horizontal"
android:autoSizeMaxTextSize="45sp"
android:autoSizeMinTextSize="15sp"
android:autoSizeStepGranularity="2sp"
android:text="#string/Loginlink"
android:textAlignment="center"
android:textSize="15sp"
android:onClick="loginlinkLabelonClick"
android:clickable="true"/>
And this function
fun loginlinkLabelonClick(context:Context)
{
val urlString="http://www.google.gr"
val intent = Intent(Intent.ACTION_VIEW,Uri.parse(urlString)) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.`package`="com.android.chrome"
try
{
context.startActivity(intent)
}
catch(ex:ActivityNotFoundException)
{
intent.`package`= null
context.startActivity(intent)
}
}
The error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.reviewer.reviewer, PID: 27809
java.lang.IllegalStateException: Could not find method loginlinkLabelonClick(View) in a parent or ancestor Context for
android:onClick attribute defined on view class
android.support.v7.widget.AppCompatTextView with id 'LoginlinkLabel'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:423)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:380)
at android.view.View.performClick(View.java:6291)
at android.view.View$PerformClick.run(View.java:24931)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7425)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
But as soon as I tap the textview the application crashes and I can't seem to find what's wrong.
I'm new to Java, kotlin and Android studio.
I had a previous experience with visual studio and c# and Java / kotlin feels a bit strange
Now I'm really trying to figure out how to open urls, but I'm having trouble getting it to work
Usually when you have a click method in the xml, the argument for the method in kotlin is a view instance, see more here. So your method should look like this:
fun loginlinkLabelonClick(view:View)
{
}

Samsung Resources$NotFoundException in Editor$SuggestionsPopupWindow.initContentView()

Crash occurs on Samsung devices (J7 and S7) running Android 7.0.
I've built a tiny test app and can reproduce the crash. Single Activity that extends Activity (not AppCompatActivity), simple layout containing a single EditText with inputType="text". Target SDK is 8.
When positioning the cursor in the EditText and typing, words are suggested and words are underlined. Click on some of the underlined words or complete editing in the EditText and then return to the EditText. After entering some data and clicking around inside the EditText, the app will crash with this stacktrace:
06-01 18:56:37.990 10339-10339/sharpmind.de.samsungtest W/ResourceType: No package identifier when getting value for resource number 0x00000000
06-01 18:56:37.991 10339-10339/sharpmind.de.samsungtest D/AndroidRuntime: Shutting down VM
06-01 18:56:37.992 10339-10339/sharpmind.de.samsungtest E/AndroidRuntime: FATAL EXCEPTION: main
Process: sharpmind.de.samsungtest, PID: 10339
android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:202)
at android.content.res.Resources.loadXmlResourceParser(Resources.java:2970)
at android.content.res.Resources.getLayout(Resources.java:1986)
at android.view.LayoutInflater.inflate(LayoutInflater.java:425)
at android.view.LayoutInflater.inflate(LayoutInflater.java:378)
at android.widget.Editor$SuggestionsPopupWindow.initContentView(Editor.java:3704)
at android.widget.Editor$PinnedPopupWindow.<init>(Editor.java:3395)
at android.widget.Editor$SuggestionsPopupWindow.<init>(Editor.java:3683)
at android.widget.Editor.replace(Editor.java:432)
at android.widget.Editor$3.run(Editor.java:2359)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
With target SDK set to 14, the crash does not occur.
If I disable the autocorrect and word suggestions (which isn't that easy to do on a Samsung device), the crash also does not occur. But this makes my users really really angry, so it isn't a viable solution.
Activity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Layout:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:minHeight="200dp"
android:inputType="text"
android:layout_height="wrap_content"/>
</RelativeLayout>

Categories

Resources