yes
yes, I am sorry that I cant offer more information about this exception except for this stack trace because the crash report was collected from google analytics, I have no idea to reappear this exception.
Environment:
OS: macOS Sierra 10.12.6
Node: 8.4.0
Yarn: 0.27.5
npm: 5.4.0
Android Studio: 3.0
Packages: (wanted => installed)
react-native: 0.51.0 => 0.51.0
react: 16.0.0-alpha.12 => 16.0.0-alpha.12
Target Platform: Android (7.1.1)
mobile:MIX 2
android:7.1.1
java.lang.NullPointerException:
tempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference at
android.graphics.drawable.DrawableContainer$DrawableContainerState.getChild(DrawableContainer.java:888) at
android.graphics.drawable.DrawableContainer.selectDrawable(DrawableContainer.java:466) at
android.graphics.drawable.StateListDrawable.onStateChange(StateListDrawable.java:104) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.graphics.drawable.DrawableWrapper.onStateChange(DrawableWrapper.java:331) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.graphics.drawable.LayerDrawable.onStateChange(LayerDrawable.java:1488) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.view.View.drawableStateChanged(View.java:18002) at
android.widget.TextView.drawableStateChanged(TextView.java:4097) at
android.view.View.refreshDrawableState(View.java:18071) at
android.view.View.setPressed(View.java:8543) at
android.view.View.setPressed(View.java:8521) at
android.view.View.onTouchEvent(View.java:11218) at
android.widget.TextView.onTouchEvent(TextView.java:8467) at
com.facebook.react.views.textinput.ReactEditText.onTouchEvent(ReactEditText.java:150)
Facing Same Issue.
Same here [email protected]
com.facebook.react.views.textinput.ReactEditText.onTouchEvent
ReactEditText.java - line 163
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
1
android.graphics.drawable.DrawableContainer$DrawableContainerState.getChild DrawableContainer.java:884
2
android.graphics.drawable.DrawableContainer.selectDrawable DrawableContainer.java:466
3
android.graphics.drawable.StateListDrawable.onStateChange StateListDrawable.java:104
4
android.graphics.drawable.Drawable.setState Drawable.java:736
5
android.graphics.drawable.DrawableWrapper.onStateChange DrawableWrapper.java:331
6
android.graphics.drawable.Drawable.setState Drawable.java:736
7
android.view.View.drawableStateChanged View.java:19223
8
android.widget.TextView.drawableStateChanged TextView.java:4673
9
android.view.View.refreshDrawableState View.java:19292
10
android.view.View.setPressed View.java:9135
11
android.view.View.setPressed View.java:9113
12
android.view.View.onTouchEvent View.java:12357
13
android.widget.TextView.onTouchEvent TextView.java:10095
14
com.facebook.react.views.textinput.ReactEditText.onTouchEvent ReactEditText.java:163
Same Issue
Same issue. Same logtrace
Same here on RN 44.0
+1 anotha' one
Guys restarting the packager and clearing cache worked for me!
Same issue for me. I am using RN 0.51.0 and react-native-material-textfield 0.12.0.
I am facing this issues as well. The strange thing is that it is very hard to track the error as the stack trace does not contain any useful information. I even do not know what where the error could be.
Will update here If i find the solution
Same error happening on RN 0.52.0.
Thanks for posting this! It looks like you may not be using the latest version of React Native, v0.53.0, released on January 2018. Can you make sure this issue can still be reproduced in the latest version?
I am going to close this, but please feel free to open a new issue if you are able to confirm that this is still a problem in v0.53.0 or newer.
Same issue on 0.53.3
Same issue
@react-native-bot Need to reopen issue
facing the same issue with Android 8
Same here. React native 0.53.3, SM-T550, API Level 25 (Android 7.0)
this issue just popped up with me, React native 0.53.3 - Android 8.1.
React native 0.53.3, android 8, same issue
Same issue, react-native 0.53.0 and android 8. It strange cause this error seems to appears randomly. I can't find any exact steps to reproduce it.
Have a production app running RN 0.54.2 and this seems to affect a few users running Android 8.0.0 on app startup.
Why is this issue closed? Some of us are facing this issue in production environment, so "restarting the packager" is not an acceptable solution.
This issue needs to be reopened since it affects current version.
I am also facing stack traces that might be related:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875)
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158)
at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433)
at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258)
at android.view.View.computeOpaqueFlags(View.java:16791)
at android.view.View.setBackgroundDrawable(View.java:21710)
at android.view.View.setBackground(View.java:21603)
at android.view.View.<init>(View.java:5547)
at android.widget.TextView.<init>(TextView.java:1135)
at android.widget.EditText.<init>(EditText.java:107)
at android.widget.EditText.<init>(EditText.java:103)
at android.widget.EditText.<init>(EditText.java:99)
at android.widget.EditText.<init>(EditText.java:95)
at com.facebook.react.views.textinput.ReactEditText.<init>(ReactEditText.java:92)
at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:94)
at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:65)
at com.facebook.react.uimanager.ViewManager.createView(ViewManager.java:46)
at com.facebook.react.uimanager.NativeViewHierarchyManager.createView(NativeViewHierarchyManager.java:218)
at com.facebook.react.uimanager.UIViewOperationQueue$CreateViewOperation.execute(UIViewOperationQueue.java:150)
at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.dispatchPendingNonBatchedOperations(UIViewOperationQueue.java:923)
at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.doFrameGuarded(UIViewOperationQueue.java:895)
at com.facebook.react.uimanager.GuardedFrameCallback.doFrame(GuardedFrameCallback.java:31)
at com.facebook.react.modules.core.ReactChoreographer$ReactChoreographerDispatcher.doFrame(ReactChoreographer.java:136)
at com.facebook.react.modules.core.ChoreographerCompat$FrameCallback$1.doFrame(ChoreographerCompat.java:107)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:909)
at android.view.Choreographer.doCallbacks(Choreographer.java:723)
at android.view.Choreographer.doFrame(Choreographer.java:655)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.DrawableContainer$DrawableContainerState$ConstantStateFuture.get(android.graphics.drawable.DrawableContainer$DrawableContainerState)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getChild(DrawableContainer.java:823)
at android.graphics.drawable.DrawableContainer.selectDrawable(DrawableContainer.java:452)
at android.graphics.drawable.StateListDrawable.onStateChange(StateListDrawable.java:104)
at android.graphics.drawable.Drawable.setState(Drawable.java:680)
at android.graphics.drawable.DrawableWrapper.onStateChange(DrawableWrapper.java:279)
at android.graphics.drawable.Drawable.setState(Drawable.java:680)
at android.graphics.drawable.LayerDrawable.onStateChange(LayerDrawable.java:1381)
at android.graphics.drawable.Drawable.setState(Drawable.java:680)
at android.view.View.drawableStateChanged(View.java:17003)
at android.widget.TextView.drawableStateChanged(TextView.java:3984)
at android.view.View.refreshDrawableState(View.java:17067)
at android.view.View.setPressed(View.java:7914)
at android.view.View.setPressed(View.java:7892)
at android.view.View.access$2900(View.java:708)
at android.view.View$CheckForTap.run(View.java:21187)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
@grabbou can we re-open this issue?
Same issue here android 8.0 api 26
Same on 0.54.2.
I've narrowed it down to a <TextInput>
being rendered within in a FlatList. When I replace this with a <Text>
, the issue disappears.
Please reproduce with the latest version available now and I will reopen this.
Same here @radko93
Android 8.1 API 27
"dependencies": {
"react": "16.3.1",
"react-native": "0.55.1",
"react-native-linear-gradient": "^2.4.0",
"react-native-vector-icons": "^4.6.0",
"react-navigation": "^1.5.11"
},
Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
createAllFutures
DrawableContainer.java:875
getOpacity
DrawableContainer.java:1158
getOpacity
DrawableContainer.java:433
getOpacity
InsetDrawable.java:258
computeOpaqueFlags
View.java:15698
setBackgroundDrawable
View.java:20502
setBackground
View.java:20395
View.java:5238
TextView.java:826
EditText.java:88
EditText.java:84
EditText.java:80
EditText.java:76
setThemedContext
ReactTextInputShadowNode.java:80
createView
UIImplementation.java:282
createView
UIManagerModule.java:366
invoke
Method.java
invoke
JavaMethodWrapper.java:372
invoke
JavaModuleWrapper.java:160
run
NativeRunnable.java
handleCallback
Handler.java:790
dispatchMessage
Handler.java:99
dispatchMessage
MessageQueueThreadHandler.java:29
loop
Looper.java:164
run
MessageQueueThreadImpl.java:192
run
Thread.java:764
Same issue
package.json
"dependencies": {
"react": "16.3.1",
"react-native": "0.55.2",
},
build.gradle
compileSdkVersion 26
buildToolsVersion "26.0.2"
minSdkVersion 16
Same issue.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getChild(DrawableContainer.java:888)
at android.graphics.drawable.DrawableContainer.selectDrawable(DrawableContainer.java:466)
at android.graphics.drawable.StateListDrawable.onStateChange(StateListDrawable.java:104)
at android.graphics.drawable.Drawable.setState(Drawable.java:735)
at android.graphics.drawable.DrawableWrapper.onStateChange(DrawableWrapper.java:331)
at android.graphics.drawable.Drawable.setState(Drawable.java:735)
at android.view.View.drawableStateChanged(View.java:18038)
at android.widget.TextView.drawableStateChanged(TextView.java:4108)
at android.view.View.refreshDrawableState(View.java:18107)
at android.view.View.setPressed(View.java:8536)
at android.view.View.setPressed(View.java:8514)
at android.view.View.onTouchEvent(View.java:11262)
at android.widget.TextView.onTouchEvent(TextView.java:8489)
at com.facebook.react.views.textinput.ReactEditText.onTouchEvent(ReactEditText.java:162)
at android.view.View.dispatchTouchEvent(View.java:10054)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2663)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2336)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2663)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2336)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2663)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2336)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2663)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2336)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2663)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2336)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2663)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2336)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2663)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2336)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2663)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2336)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2663)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2336)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2663)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2336)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2663)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2336)
at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:432)
at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1841)
at android.app.Activity.dispatchTouchEvent(Activity.java:3233)
at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:394)
at android.view.View.dispatchPointerEvent(View.java:10286)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4514)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4370)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3883)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3953)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3911)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4053)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3919)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4110)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3883)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3953)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3911)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3919)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3883)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6359)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6333)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6288)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6469)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:193)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:323)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:6295)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:790)
Android: 7.1.1
React-Native: 0.48.3
Same issue.
same issue ,in the production environment,my device is HUAWEI(LLD-AL10) 8.0.0 ,I am currently using React Native 0.46.2,thanks
Getting the same issue when using the latest version of react-native (0.55.3). The issue seems to be related to TextInput in a FlatList as mentioned above. Getting the error in android 8.0 and 8.1. Any workarounds to avoid this issue?
I can reproduce this bug by creating a new React Native project with react-native init and changing the App.js to
import React, { Component } from 'react';
import {
StyleSheet,
TextInput,
View
} from 'react-native';
type Props = {};
export default class App extends Component<Props> {
render() {
const inputs = Array.apply(null, Array(256)).map((_, i) => i)
return (
<View>
{inputs.map(i => <TextInput key={i} />)}
</View>
);
}
}
I was running this on a Galaxy S8 with Android 8.0.0 from MacOS 10.13.3.
"dependencies": {
"react": "16.3.1",
"react-native": "0.55.3"
},
I don't know if the error is not directly tied to the number of TextInputs, but this is the only way I could reproduce this bug in a fairly reliable fashion. With 128 inputs I didn't get this error on every restart but after a few reloads it did come up. At 256 bare TextInputs I don't think I have been able to start the application without getting the error. I also noticed that adding elements between the TextInputs seemed to reduce the likelihood of getting this error, so it is likely not directly tied to the number of TextInputs. I tried this in my current application and adding hundreds of TextInputs to the starting screen did also trigger this error, but my other views with similar amounts of TextInputs wrapped in other elements do not seem to always trigger this error as I have some in my application.
I have the same issue. I was running this on a Huawei P10 with Android 8.0.0.
"react": "^16.2.0",
"react-native": "^0.55.0",
Screenshot
It seems like the problem is in the TextInputs. This happens on my Huawei P10 (Android 8.0.0). Is there a fix for this already?
Android:7.1.1
"react-native": "0.53.3",
Thanks for posting this! It looks like your issue may refer to an older version of React Native. Can you reproduce the issue on the latest release, v0.55?
Thank you for your contributions.
I'm facing the same issue. It's related to the TextInput component. Even a single TextInput being rendered in a screen is causing this error. Are there any workarounds?
react-native: 0.55
react: 16.3.1
I change the ReactEditText constructor “ super“, it looks not happen,
but comment out “underlineColorAndroid ”
https://github.com/yuanboGeng/react-native/commit/36f7949f9a3e9c1f3b10df43a9f495f9f8712a1f
react-native: 0.53.3
react: 16.2.0
This started happening for me after upgrading my emulator to API level 26 from API level 21
I had this error appearing for no reason while developing. I cleaned out my /build folders and ran a run-android
again. The issue disappeared. Really weird. I hope for some of you a clean build will resolve this.
Having this same problem. One small difference - in mine I am nesting TextInputs inside of a VirtualizedList (the parent of FlatList) and I only get the issue when I start scrolling around in that list, even then only getting it intermittently rather than all the time. Similarly to others, this is happening in a production environment, so restarting the packager is not an option.
Based on some digging, appears related to an old issue in Android itself: https://issuetracker.google.com/issues/37068452
If that is the underlying problem, this would be solved by just upgrading the compileSdk and support library versions in the RN project. No idea the LoE on that, though.
Update: trying to force subprojects to use a higher version of the build tools and compileSdk did not solve this problem for my project, as explained in this SO post. Not sure if I just applied those higher versions wrong, if my build setup isn't treating RN as a subproject in that way, or if it was actually not a valid solution for the problem here.
EDIT 2: It appears that ReactEditText isn't even using the support library version of EditText (which would be AppCompatEditText), which explains why upgrading the support library didn't do anything. I'm looking into this - it'll take a couple more updates than just changing the inheritance to get this to work, but it _might_ be the right solution to this problem.
EDIT 3: It was not the solution. I am no longer confident that this issue is the same as the linked AOSP one.
I can say that it doesn't appear to matter what kind of ScrollView you put your text in - I was able to reproduce in both VirtualizedList and ScrollView, and many in this thread have done it with a FlatList.
i have this same on production
I also am facing this issue. Running cd android ; ./gradlew clean ; cd .. ; react-native run-android
works for me as @mbret pointed out (thanks!)
Great, but what about apps on production with real clients? :|
Sorry @ahanusek, I am not saying this resolves the issue, I am just saying that in development this worked for me (in hopes that it will also help someone else).
But even for development it's not a solution. Ok, you clean your build, start app again, but if you use inputs "hardly" you still could get this error again.
@ahanusek Yes, I agree with you, and am in no way arguing with you. This isn't a solution, but for me, and for now, it has worked to allow me to continue to develop
Also seeing this, v0.55.4:
Fairly certain I don't have a TextField in a FlatList or VirtualizedList, fwiw. This is happening in our production build.
Seeing this issue in v0.55.4
. And yes we're using a TextInput
in a List.
Happens in react 0.55. Following
Also happens in react native 0.55, using input in flat list.
Making an actual post here in case people don't see my edited comment:
I can say that it doesn't appear to matter what kind of ScrollView you put your text in - I was able to reproduce in both VirtualizedList and ScrollView, and many in this thread have done it with a FlatList.
Or, to phrase it differently, the problem boils down to
RN Crashes when loading a very large number of TextInputs. Usually this happens in a ScrollView (or some descended component class of one), but one person got it to happen in a plain View
Same issue
I am also facing same issue.
Strangely enough, this didn't start happening to me until last night and I've been rendering TextInputs the same way for well over a month now in development.
Android version 9
React "16.3.1"
React-Native "~0.55.2"
We also had been facing a similar issue in our code
Crash logs:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875)
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158)
at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433)
at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258)
at android.view.View.computeOpaqueFlags(View.java:16791)
at android.view.View.setBackgroundDrawable(View.java:21710)
at android.view.View.setBackground(View.java:21603)
at android.view.View.
at android.widget.TextView.
at android.widget.EditText.
at android.widget.EditText.
at android.widget.EditText.
at android.widget.EditText.
at com.facebook.react.views.textinput.ReactEditText.
What seems to be the issue here?
Tried a few investigations:
- over 1000 edittext work in pure android app
- some 200 ReactTextInput fails as indentified here
How we solved or made it work?
[1] Move the new EditText(context) call on UI thread as well and made measure of ShadowNode async but waiting till this EditText object has been created on UI thread - basically rewrote the shadow node setThemedContext and measure functions
Shortcomings: thread switch for every RTI
[2] Create EditText using layout inflater on Native module while specifying null for background and create only once the background drawable by creating an EditText on UI thread and caching its background drawable at shadowNode level. This drawable is used to set the background of the dummyEditTexts created using layout inflater to get the measure consider the drawable borderline paddings. In this case measure only needs to wait once for the Drawable creation
I have tested both and they work fine for 1024 ReactTextInput.
Note: Base on investigation, this doesn't really seem to be the most elegant solution but it works with minimal changes and proves the analysis of the issue.
Suggestions and criticisms are most welcome!
Shadow Node code:
`package
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.EditText;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.common.annotations.VisibleForTesting;
import com.facebook.react.uimanager.Spacing;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.UIViewOperationQueue;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.views.text.ReactBaseTextShadowNode;
import com.facebook.react.views.text.ReactTextUpdate;
import com.facebook.react.views.textinput.ReactTextInputLocalData;
import com.facebook.react.views.view.MeasureUtil;
import com.facebook.yoga.YogaMeasureFunction;
import com.facebook.yoga.YogaMeasureMode;
import com.facebook.yoga.YogaMeasureOutput;
import com.facebook.yoga.YogaNode;
import
import javax.annotation.Nullable;
// NOTE: This class is not much different from ReactTextInputShadowNode expect in the mechanism of
// setting theme context and performing measure
public class ReactTextInputShadowNode extends ReactBaseTextShadowNode implements YogaMeasureFunction
{
@VisibleForTesting
public static final String PROP_TEXT = "text";
private static Drawable sDummyEditTextBackgroundDrawable = null;
private int mMostRecentEventCount = UNSET;
private @Nullable EditText mDummyEditText;
private @Nullable ReactTextInputLocalData mLocalData;
// Represents the {@code text} property only, not possible nested content.
private @Nullable String mText = null;
public ReactRichTextInputShadowNode()
{
mTextBreakStrategy = (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) ?
0 : Layout.BREAK_STRATEGY_SIMPLE;
setMeasureFunction(this);
}
@Override
public void setThemedContext(final ThemedReactContext themedContext)
{
super.setThemedContext(themedContext);
// Inflating with layout using background as null because new EditText(context) call
// can cause NullPointer Exception during a race scenario of UI thread performing EditText
// creation with background at the same time
// BACKGROUND:
// ---------------
// SparseArray is not threadsafe and at the same time there is logic of gc() inside it
// SparseArray is used by DrawableContainerState and new DrawableContainerState may get
// created using the an existing constant state's drawable futures(this is SparseArray) by
// cloning
// The above is a recipe for a multi-threaded null pointer exception and it happens as below
// - Native module thread working on RTI shadow node creation and its lifecycle does a
// new EditText(reactThemedContext) which in turn results in background drawable to be
// set and finally invoking the SparseArray thread unsafe code
// - UI thread meanwhile could be used to create the display EditText of some other RTI
// at the same time leading up to the same SparseArray thread unsafe code
// - Null pointer exception happens when the gc() is invoked and simultaneously clone is
// being done for the same object giving rise to a partially gc-ed object. Something
// like an item from values array was removed and null-ed but the noOfItems flag is yet
// to be updated, so cloned object has one item less than specified in noOfItems flag
// and iteration can cause null pointer exception for the deleted index.
//
// Solution:
// ------------
// Create EditText using layout inflater on Native module while specifying null for
// background and create only once the background drawable by creating an EditText on UI
// thread and caching its background drawable at shadowNode level. In this case measure only
// needs to wait once for the Drawable creation
// Shortcomings: Ideally we would like to create the Drawable on the same Native module
// thread but not able to access android.internal stylable ids to
// approach this solution
LayoutInflater sInflater =
(LayoutInflater) themedContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
EditText editText =
(EditText) sInflater.inflate(R.layout.dummy_edit_text, null, false);
// creating the EditText theme background on UI thread async to prevent above mentioned race
// scenario
if (sDummyEditTextBackgroundDrawable == null) {
themedContext.runOnUiQueueThread(new Runnable() {
@Override
public void run() {
sDummyEditTextBackgroundDrawable = new EditText(themedContext).getBackground();
}
});
}
mDummyEditText = editText;
}
@Override
public long measure(YogaNode node, float width, YogaMeasureMode widthMode, float height,
YogaMeasureMode heightMode)
{
// measure() should never be called before setThemedContext()
EditText editText = Assertions.assertNotNull(mDummyEditText);
if (mLocalData == null || sDummyEditTextBackgroundDrawable == null)
{
// No local data or edit text background drawable, no intrinsic size.
return YogaMeasureOutput.make(0, 0);
}
// {@code EditText} has by default a border at the bottom of its view
// called "underline". To have a native look and feel of the TextEdit
// we have to preserve it at least by default.
// The border (underline) has its padding set by the background image
// provided by the system (which vary a lot among versions and vendors
// of Android), and it cannot be changed.
// So, we have to enforce it as a default padding.
// Sharing the same background drawable is not working in measure and Edit Text features.
// Hence, cloning.
editText.setBackground(sDummyEditTextBackgroundDrawable.getConstantState().newDrawable());
setDefaultPadding(Spacing.START, editText.getPaddingStart());
setDefaultPadding(Spacing.TOP, editText.getPaddingTop());
setDefaultPadding(Spacing.END, editText.getPaddingEnd());
setDefaultPadding(Spacing.BOTTOM, editText.getPaddingBottom());
// We must measure the EditText without paddings, so we have to reset them.
editText.setPadding(0, 0, 0, 0);
// This is needed to fix an android bug since 4.4.3 which will throw an NPE in measure,
// setting the layoutParams fixes it: https://code.google.com/p/android/issues/detail?id=75877
editText.setLayoutParams(
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
mLocalData.apply(editText);
editText.measure(
MeasureUtil.getMeasureSpec(width, widthMode),
MeasureUtil.getMeasureSpec(height, heightMode));
return YogaMeasureOutput.make(editText.getMeasuredWidth(), editText.getMeasuredHeight());
}
@Override
public boolean isVirtualAnchor()
{
return true;
}
@Override
public boolean isYogaLeafNode()
{
return true;
}
@Override
public void setLocalData(Object data)
{
Assertions.assertCondition(data instanceof ReactTextInputLocalData);
mLocalData = (ReactTextInputLocalData) data;
// Telling to Yoga that the node should be remeasured on next layout pass.
dirty();
// Note: We should NOT mark the node updated (by calling {@code markUpdated}) here
// because the state remains the same.
}
@ReactProp(name = "mostRecentEventCount")
public void setMostRecentEventCount(int mostRecentEventCount)
{
mMostRecentEventCount = mostRecentEventCount;
}
@ReactProp(name = PROP_TEXT)
public void setText(@Nullable String text)
{
mText = text;
markUpdated();
}
public @Nullable String getText()
{
return mText;
}
@Override
public void setTextBreakStrategy(@Nullable String textBreakStrategy)
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
{
return;
}
if (textBreakStrategy == null || "simple".equals(textBreakStrategy))
{
mTextBreakStrategy = Layout.BREAK_STRATEGY_SIMPLE;
}
else if ("highQuality".equals(textBreakStrategy))
{
mTextBreakStrategy = Layout.BREAK_STRATEGY_HIGH_QUALITY;
}
else if ("balanced".equals(textBreakStrategy))
{
mTextBreakStrategy = Layout.BREAK_STRATEGY_BALANCED;
}
else
{
throw new JSApplicationIllegalArgumentException("Invalid textBreakStrategy: " +
textBreakStrategy);
}
}
@Override
public void onCollectExtraUpdates(UIViewOperationQueue uiViewOperationQueue)
{
if (mMostRecentEventCount != UNSET)
{
ReactTextUpdate reactTextUpdate =
new ReactTextUpdate(
spannedFromShadowNode(this, getText()),
mMostRecentEventCount,
mContainsImages,
getPadding(Spacing.LEFT),
getPadding(Spacing.TOP),
getPadding(Spacing.RIGHT),
getPadding(Spacing.BOTTOM),
mTextAlign,
mTextBreakStrategy);
uiViewOperationQueue.enqueueUpdateExtraData(getReactTag(), reactTextUpdate);
}
}
@Override
public void setPadding(int spacingType, float padding)
{
super.setPadding(spacingType, padding);
markUpdated();
}
}`
Dummy edit text Layout file
<?xml version="1.0" encoding="utf-8"?>
<EditText
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dummy_edit_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"
/>
@sayantanbugs do you have a piece of code for this solution? Thanks!
Updated my last comment to include ShadowNode code and the layout used for inflating dummy edittext
@sayantanbugs - That is some great 🕵️ work! We'll try it in our project and report back! Thanks!
Same issue
ReactNative: 0.55.4
Android: 8.0
@sayantanbugs can you please provide a diff/patch?
Same issue. Reported via Crashlytics without much other detail, so really hard to troubleshoot.
RN 55.3
Android 8
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875)
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158)
at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433)
at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258)
at android.view.View.computeOpaqueFlags(View.java:16791)
at android.view.View.setBackgroundDrawable(View.java:21710)
at android.view.View.setBackground(View.java:21603)
at android.view.View.<init>(View.java:5547)
at android.widget.TextView.<init>(TextView.java:1135)
at android.widget.EditText.<init>(EditText.java:107)
at android.widget.EditText.<init>(EditText.java:103)
at android.widget.EditText.<init>(EditText.java:99)
at android.widget.EditText.<init>(EditText.java:95)
at com.facebook.react.views.textinput.ReactTextInputShadowNode.setThemedContext(ReactTextInputShadowNode.java:80)
at com.facebook.react.uimanager.UIImplementation.createView(UIImplementation.java:282)
at com.facebook.react.uimanager.UIManagerModule.createView(UIManagerModule.java:366)
at java.lang.reflect.Method.invoke(Method.java)
at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372)
at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:160)
at com.facebook.react.bridge.queue.NativeRunnable.run(NativeRunnable.java)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)
at android.os.Looper.loop(Looper.java:164)
at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:192)
at java.lang.Thread.run(Thread.java:764)
This is the main cause of our app crashing in production. When / how can this happen?
Same here in production build.
Happens when editing text. It's random.
react: 16.3.0
react-native:0.54.4
same issue, how to fix it ?
^^^More people should attempt to fix the problem with @sayantanbugs solution. Just locate your ReactTextInputShadowNode.java
file in your react-native
folder and swap out the code he provided is his post. You may be pleasantly surprised.
After a week since I've done so, I am glad to report back that the error has only happened again once. BUT this time it was different.. I was able to restart the app and have it working normally without needing to reinstall the app via react-native run-android
which was really a pain because before I would literally lose access to a couple screens that rendered those TextInputs. I will continue to take note of the error if it appears again but so far I think it works near perfectly on my end. Excellent debugging, @sayantanbugs!
@Friendly-Robot imo it's not a solution. It's a workaround at best. This is happening in production code where we can't just patch up an untested solution which you even admit doesn't fix it.
If it's annoying on dev, sure, by all means. But I don't think it's wise to motivate people to use it as a solution. Perhaps as a basis for a PR though.
Agreed with @Friendly-Robot (nonetheless, thank you @sayantanbugs ). Anyone from RN here? Do you think that the patch can make it to the RN repo and be tested?
Ok, I was finally able to test @sayantanbugs 's approach, but it did not seem to work for me (it's also based on non-master code). However, as a temporary solution (vs a framework solution), you can provide your own copy of ReactEditText
with a patched drawableStateChanged()
method:
@Override
protected void drawableStateChanged() {
try {
super.drawableStateChanged();
} catch (Exception e) {
Timber.e("Prevented Drawable crash!");
}
}
This is literally just a patch, but at least the application will not crash. The Text Input is still responsive and works as expected, as far as I could tell.
When reproducing the (now fixed) crash, I could see that this actual exception happened a few times in quick succession.
EDIT:
Hmmm... while everything seems to work, it appears that the Drawable state has been corrupted permanently. Even after creating a completely new view with new Text Inputs, touching any text input will cause the message to show up again. Fortunately it only shows when clicking on the input and not when entering text.
I've been playing with my view and transition tonight, I got this error like twenty times ... I was not doing anything but clicking on my navigations to test transitions between views. I guess that's a big deal :/
Thanks @Friendly-Robot for testing the solution!
Agree to most views on my solution being a patch and I did mention that in my original post that includes the solution. The reason it could still be used in my project is because we have created a more feature rich RTI on our side extending the RN RTI. Hence we could use my solution in the ShadowNode implementation of my custom RTI. Infact in our project we maintain a modified version of RN to fix many RN bugs/use cases, and hence we can also get these changes into that.
I do plan to give this a second look on other possibilities as I had to solve the burning issue at hand in a matter of few days during that time.
Thanks all for your feedback!
@davidmontemayor , if that issue of drawable state is being noticed with my fix, you could modify the shadowNode to simply do new EditText() always but moving that call to UIthread and thus not handling the drawable in anyway. That would definitely fix it. I did not want to do that as it would be an inefficient way to switch threads when the real purpose in the Shadow node was simply to get the background's border padding but the mechanism employed by RN is not behaving so but having a sideeffect.
This is making us think that we might be rewriting the ShadowNode ourselves such that we don't need the EditText object the way its being used at this point other than using the measure function.
Happens for me too. I'm using ScrollView.
I have various controls (radio, list, edittext, etc) in a scrollview. I'd say I have a max of 10 controls, so not a huge list.
It's difficult to reproduce though. It seems to happen at random times, but I think I'm tracking it down to bringing the app into foreground from the background when I have ScrollView on screen (with edittext controls in it).
Not 100% sure though
I'm wondering if it's related to Android support lib version.
Come on FB, fix this bug.
It's hard to create production quality apps when we have random crashes like this.
com.facebook.react.views.textinput.ReactEditText
RN 0.54
Android SDK 27
Phone 8.1
Having this issue as well, also using ScrollViews. @davidmontemayor, could you direct his RN newb to which file you edited by the directory structure? I have an app out on the market which the crash is affecting irritatingly and was hoping to catch the error like you did until a fix happens. Do you have an example of the file that you used?
Same:
NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
@Squidski - Unfortunately the "catch 'em all" fix gets extremely tricky once you start dealing with the EditText
initialization failures. For background, there are _two_ different ways that this issue manifests:
android.widget.EditText.<init>(EditText.java:95)
)android.widget.TextView.onTouchEvent(TextView.java:8467)
)The key thing is to replace the created view in ReactTextInputShadowNode
. Instead of letting it do new EditText(getThemedContext())
, create your own class that extends from EditText
. You can then catch the exception caused by the second path in drawableStateChanged()
.
The harder part is fixing the initialization errors. For that you need to create a "Drawable Wrapper" class that can be used to wrap any ol' drawable that is passed into EditText.setBackground()
. This wrapper should then catch the exceptions being thrown from the delegate.
This issue still happens randomly with my app with the latest version of React Native + latest JSC + latest gradle as of 25 July 2018
React Native Environment Info:
System:
OS: macOS High Sierra 10.13.3
CPU: x64 Intel(R) Core(TM) i5-5250U CPU @ 1.60GHz
Memory: 26.19 MB / 8.00 GB
Shell: 5.3 - /bin/zsh
SDKs:
iOS SDK:
Platforms: iOS 11.4, macOS 10.13, tvOS 11.4, watchOS 4.3
IDEs:
Android Studio: 3.1 AI-173.4720617
Xcode: 9.4.1/9F2000 - /usr/bin/xcodebuild
npmPackages:
react: ^16.4.1 => 16.4.1
react-native: ^0.56.0 => 0.56.0
npmGlobalPackages:
react-native-cli: 2.0.1
JSC: org.webkit:android-jsc:r224109
Gradle: 4.8.1
I've started seeing this issue with Android 8.0.0 and with RN 0.55.3. Are their any workarounds for this or a PR perhaps?
Having the same problem randomly too with a FlatList of TextInputs 😞
java.lang.NullPointerExceptionMainActivity
java.lang.NullPointerException Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
DrawableContainer.java:875 android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures
DrawableContainer.java:1158 android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity
DrawableContainer.java:433 android.graphics.drawable.DrawableContainer.getOpacity
InsetDrawable.java:258 android.graphics.drawable.InsetDrawable.getOpacity
View.java:15842 android.view.View.computeOpaqueFlags
View.java:20658 android.view.View.setBackgroundDrawable
View.java:20551 android.view.View.setBackground
View.java:5290 android.view.View.<init>
TextView.java:832 android.widget.TextView.<init>
EditText.java:88 android.widget.EditText.<init>
EditText.java:84 android.widget.EditText.<init>
EditText.java:80 android.widget.EditText.<init>
EditText.java:76 android.widget.EditText.<init>
ReactTextInputShadowNode.java:80 com.facebook.react.views.textinput.ReactTextInputShadowNode.setThemedContext
UIImplementation.java:282 com.facebook.react.uimanager.UIImplementation.createView
UIManagerModule.java:366 com.facebook.react.uimanager.UIManagerModule.createView
Method.java:-2 java.lang.reflect.Method.invoke
JavaMethodWrapper.java:372 com.facebook.react.bridge.JavaMethodWrapper.invoke
JavaModuleWrapper.java:160 com.facebook.react.bridge.JavaModuleWrapper.invoke
NativeRunnable.java:-2 com.facebook.react.bridge.queue.NativeRunnable.run
Handler.java:790 android.os.Handler.handleCallback
Handler.java:99 android.os.Handler.dispatchMessage
MessageQueueThreadHandler.java:29 com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage
Looper.java:164 android.os.Looper.loop
MessageQueueThreadImpl.java:192 com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run
Thread.java:764 java.lang.Thread.run
Based on reading and debugging, I've decided to try the following this weekend...
Remove all underlineColorAndroid calls from my code (I'm using react-native-elements 0.19)
Update my Android styles to be following. This will force all EditText controls to have transparent background
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:editTextStyle">@style/AppEditTextStyle</item>
<item name="editTextStyle">@style/AppEditTextStyle</item> <!-- For compatibility with the support library -->
</style>
<style name="AppEditTextStyle" parent="@style/Widget.AppCompat.EditText">
<item name="android:background">@android:color/transparent</item>
</style>
</resources>
Test - Test - Test. Problem is difficult to reproduce. Although a client stumbled upon it this morning.
As a fallback, implement fix from @sayantanbugs
4.1 Update react-native-elements to 1.0xx beta
Readings
https://issuetracker.google.com/issues/37068452
https://github.com/facebook/react-native/issues/18214
RN 0.54
React-native-elements 0.19
Happens on RN 0.56.0 Android 8.1.0
Wondering if there are plans to move it forward.
Try replacing all instances of
underlineColorAndroid={"transparent"}
with
underlineColorAndroid={"#00000000"}
Having this issue. Solve it with something tricky. Make a button that handle render of current input. So we have FlatList of buttons and only TextInput we edit right now. Without ref we need double click for starting edit input
handleShowInput(key) {
const { inputKeyToShow } = this.state;
if (!inputKeyToShow) {
this.setState({
inputKeyToShow: key,
}, () => this.textInput.focus());
} else {
this.setState({
inputKeyToShow: null,
});
}
}
{inputKeyToShow !== key ?
(
<TouchableOpacity
...
onPress={() => this.handleShowInput(key)}
>
<Text>{value}</Text>
</TouchableOpacity>
) :
(
<TextInput
...
ref={ref => (this.textInput = ref)}
value={value}
onEndEditing={() => this.handleShowInput(key)}
/>
)
}
@WilliamAlexander @paulroy Did your solution work?
@xstreamcl the solution I posted is working so far. Over 2 weeks and I've not seen the issue.
Needs more testing though ;)
This issue has been causing our app to crash in production as well. It's a nasty bug, because it is really difficult to reproduce. We've found a promising fix for our app, and I'd like to share our findings here to hopefully save others some time & frustration.
This bug has caused our app to crash on Samsung, Google, and LG Android devices. We've had crash reports from the following Android versions:
8.0.0
8.1.0
7.1.1
Our app is running:
react-native
: 0.53.0react
: 16.2.0Like others have noted in this thread, the issue seems to be triggered by rendering some combination of TextInput
, FlatList
, and ScrollView
components. In our case, we have a screen containing a single TextInput
rendered above a FlatList
. When one of the items in the FlatList
is tapped, the app navigates to a new screen containing a form. This form's root component is a ScrollView
that contains a number of TextInput
components (along with some buttons and other custom components). Our app crashes when the user taps one of these FlatList
items (note that it doesn't happen _every_ time).
Reproducing this issue is difficult. In fact, we've been unable to do so. But we know that the crash occurs at this point in the workflow by watching our Appsee session recordings.
Because we can't reproduce the issue, we've had to rely on the crash logs from Appsee to debug it. I've copied the stack trace from the crash reports below (and omitted some noisy sections). It's more or less identical to the stack traces posted in this thread by others:
0 java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
1 at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875)
2 at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158)
3 at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433)
4 at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258)
5 at android.view.View.computeOpaqueFlags(View.java:16900)
6 at android.view.View.setBackgroundDrawable(View.java:21824)
7 at android.view.View.setBackground(View.java:21717)
8 at android.view.View.<init>(View.java:5577)
9 at android.widget.TextView.<init>(TextView.java:1144)
...
13 at android.widget.EditText.<init>(EditText.java:96)
14 at com.facebook.react.views.textinput.ReactEditText.<init>(ReactEditText.java:91)
15 at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:91)
16 at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:61)
...
35 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
After reading through this thread and doing a few hours or research, I found the underlineColorAndroid
prop handler in the ReactTextInputManager.java
file:
@ReactProp(name = "underlineColorAndroid", customType = "Color")
public void setUnderlineColor(ReactEditText view, @Nullable Integer underlineColor) {
// Drawable.mutate() can sometimes crash due to an AOSP bug:
// See https://code.google.com/p/android/issues/detail?id=191754 for more info
Drawable background = view.getBackground();
Drawable drawableToMutate = background.getConstantState() != null ?
background.mutate() :
background;
if (underlineColor == null) {
drawableToMutate.clearColorFilter();
} else {
drawableToMutate.setColorFilter(underlineColor, PorterDuff.Mode.SRC_IN);
}
}
The bug report linked to in the comment contains the following stack trace:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable()' on a null object reference
at android.graphics.drawable.LayerDrawable$ChildDrawable.<init>(LayerDrawable.java:1723)
at android.graphics.drawable.LayerDrawable$LayerState.<init>(LayerDrawable.java:1792)
at android.graphics.drawable.LayerDrawable.createConstantState(LayerDrawable.java:152)
at android.graphics.drawable.LayerDrawable.mutate(LayerDrawable.java:1652)
This matches the stack trace we we are encountering in our app. I don't pretend to fully understand the underlying problem, but it seems likely that the cause of our app crashing in production is due to the Drawable.mutate()
bug being triggered. This happens when we try to set the underlineColorAndroid
prop on our TextInput
component (and thus invoke the ReactTextInputManager.setUnderlineColor
method).
Our app was rendering a TextInput
with the following props, one of which was underlineColorAndroid="transparent"
:
<TextInput
ref={this.handleRef}
value={this.props.value}
autoCorrect={false}
autoCapitalize="none"
underlineColorAndroid="transparent"
onSubmitEditing={this.handleSubmit}
onChangeText={this.props.onChangeText}
onFocus={this.handleFocused}
onBlur={this.handleBlur}
clearButtonMode="always"
/>
We needed to set this prop in order to remove the underline from the TextInput
components in our app. But based on our findings, its prop handler appeared to be triggering an Android bug that caused the app to crash occasionally.
Fortunately, there is another way to remove underlines from TextInput
components on Android. You can add a line to the android/app/src/main/res/values/styles.xml
file:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowExitAnimation">@android:anim/fade_out</item>
<item name="android:windowBackground">@drawable/splash_screen</item>
+ <item name="android:editTextBackground">@android:color/transparent</item>
</style>
</resources>
Note that I've also seen the following suggested, but this did not remove the underlines for us:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowExitAnimation">@android:anim/fade_out</item>
<item name="android:windowBackground">@drawable/splash_screen</item>
</style>
+ <!-- This did *not* work for us... -->
+ <style name="AppEditTextStyle" parent="@style/Widget.AppCompat.EditText">
+ <item name="android:background">@android:color/transparent</item>
+ </style>
</resources>
This does not address the underlying issue. It is just a workaround that involves avoiding usage of the underlineColorAndroid
prop on TextInput
components.
I cannot yet say with certainty that this actually works, because I've been unable to reproduce the issue locally. We'll be deploying this change in an update to our app in the coming weeks. After that, we'll have to wait awhile to see if it occurs anymore. I'll try to report back with our findings.
Good luck to everybody wrestling with this frustrating issue! I hope this helps.
Thanks @Hopding apparently your solution is working!
@Hopding
Yep Working thanks a lot
For us, this problem, and all the similar problems where you find out a calling method on a null reference in Android are caused by not having the proper style in the app.
The thing is that most of the react-native
components -- if not all -- extends from appcompat
components; i.e. Hence, having a style like this one is mandatory:
At somewhere like: /android/app/src/main/res/values/styles.xml
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
</resources>
This happens because the appcopmat
component is not rendered in the first place and hence the view.getDrawable()
returns a null value from which you cannot call any method like: setUnderlineColor
or setColorTint
(Switches also have this problem).
In our case, because we were using react-native
to create native libraries that later on are installed in native applications we cannot control that the styles are present in the final app. Tho, at least now we are aware of that issue and we improved our documentation ;)
Hope it helps!
@sospedra Your comment makes sense, but I've checked my code and found that appcompat
already exists in my style. If you check Hopding's workaround, he also has appcompat
already.
@Hopding
This style works fine:
@WilliamAlexander, I wasn't able to get your suggestion to work. Can you include the entire style that works for you?
The other problem I'm facing is that when applying @Hopding 's fix is that it affected the layout of my multiline text input so that the keyboard covers the text input partially now. Tearing my hair out trying to fix this seemingly simple problem
Update: @Hopding 's style need to be written in this way
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:editTextStyle">@style/AppEditTextStyle</item>
</style>
<style name="AppEditTextStyle" parent="@style/Widget.AppCompat.EditText">
<item name="android:background">@android:color/transparent</item>
<item name="android:paddingTop">??dp</item>
<item name="android:paddingBottom">??dp</item>
</style>
I had to add the padding to fix the layout breaking.
@gavin-gmlab.
Here it is.
`
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<!-- Main theme colors -->
<!-- your app branding color for the app bar -->
<item name="android:colorPrimary">@color/colorPrimary</item>
<!-- darker variant for the status bar and contextual app bars -->
<item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
<!-- theme UI controls like checkboxes and text fields -->
<item name="android:colorAccent">@color/colorAccent</item>
<item name="android:editTextStyle">@style/AppEditTextStyle</item>
<item name="editTextStyle">@style/AppEditTextStyle</item> <!-- For compatibility with the support library -->
<item name="android:windowIsTranslucent">true</item>
</style>
<style name="AppEditTextStyle" parent="@style/Widget.AppCompat.EditText">
<item name="android:background">@android:color/transparent</item>
</style>
`
Removed underlineColorAndroid="transparent"
and changed style.xml
its working for me
none of the above solution worked for me, but apparently closing the app plus the packager and rerunning did..
Simply clear your app data and run again
Thanks @WilliamAlexander and @Hopding for their solution but when I change background it removes my InputText's padding also. Instead of it, I used backgroundTint and it works fine without any change in padding
````
<style name="AppEditTextStyle" parent="@style/Widget.AppCompat.EditText">
<item name="backgroundTint">@android:color/transparent</item>
</style>
````
Ok, is there any solution to this for Expo users except ejecting?
@Twishka Unfortunately you would have to eject to raw react-native as well, because Expokit has the same issues.
I'm not even setting underlineColorAndroid
anywhere in my app still got this log in my firebase console. And I have no idea how to reproduce this issue again.
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875)
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158)
at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433)
at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258)
at android.view.View.computeOpaqueFlags(View.java:15945)
at android.view.View.setBackgroundDrawable(View.java:20887)
at android.view.View.setBackground(View.java:20780)
at android.view.View.(View.java:5311)
at android.widget.TextView.(TextView.java:850)
at android.widget.EditText.(EditText.java:95)
at android.widget.EditText.(EditText.java:91)
at android.widget.EditText.(EditText.java:87)
at android.widget.EditText.(EditText.java:83)
at com.facebook.react.views.textinput.ReactEditText.(SourceFile:92)
at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(SourceFile:100)
at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(SourceFile:60)
at com.facebook.react.uimanager.ViewManager.createView(SourceFile:42)
at com.facebook.react.uimanager.NativeViewHierarchyManager.createView(SourceFile:260)
at com.facebook.react.uimanager.UIViewOperationQueue$CreateViewOperation.execute(SourceFile:200)
at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.dispatchPendingNonBatchedOperations(SourceFile:1085)
at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.doFrameGuarded(SourceFile:1056)
at com.facebook.react.uimanager.GuardedFrameCallback.doFrame(SourceFile:29)
at com.facebook.react.modules.core.ReactChoreographer$ReactChoreographerDispatcher.doFrame(SourceFile:134)
at com.facebook.react.modules.core.ChoreographerCompat$FrameCallback$1.doFrame(SourceFile:105)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:918)
at android.view.Choreographer.doCallbacks(Choreographer.java:732)
at android.view.Choreographer.doFrame(Choreographer.java:661)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:906)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:187)
at android.app.ActivityThread.main(ActivityThread.java:7025)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:514)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888)
Talking about colors I have placeHolderTextColor and borderColor to #acacac
and when some validation issue occurs borderColor to red
. Apart from that I'm not even setting underlineColorAndroid
.
Any help is appreciated.
@mddanishansari Since rn 0.56 underlineColorAndroid
is set by default, so you need the fix mentioned above.
@mddanishansari Since rn 0.56
underlineColorAndroid
is set by default, so you need the fix mentioned above.
Thanks a lot. I didn't expected reply so fast. The issue is that then all the other original native EditText
background is also transparent which looks weird. Some screens of my app are also in original native (Java).
I was just wondering how can this issue be solved actually. The solution provided is just a simple hack. Right?
Hi guys. So, using underlineColorAndroid triggers this crash somehow.
But now, in addition, underlineColorAndroid is set by default.
How can avoid using this, and fallback to styles.xml.?
Regards
Just in case this helps someone. In my case I was accidentally sending NaN in stead of the actual color value it happened to me in 'borderBottomLeftRadius' I did not have any problems with the Iphone just Android.
the solutions in this thread aren't working for me. Even when setting the underlineColorAndroid
for all my textinputs to something non transparent (I tested with '#f00'
), I still am experiencing this issue.
For me the issue doesn't occur consistently. I have a bunch of TextInputs within a ScrollView, and I have to open and close the screen multiple times for it to occur
It's not the transparency that causes the error, it's the changing of the
native color from the react native prop. It's just that almost everyone
makes the native underline transparent with the prop.
On Wed, Feb 6, 2019, 10:23 PM Adrien Pyke notifications@github.com wrote:
the solutions in this thread aren't working for me. Even when setting the
underlineColorAndroid for all my textinputs to something non transparent
(I tested with '#f00'), I still am experiencing this issue.For me the issue doesn't occur consistently. I have a bunch of TextInputs
within a ScrollView, and I have to open and close the screen multiple times
for it to occur—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/facebook/react-native/issues/17530#issuecomment-461283498,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AOG_BAlfs-GKED4gOuvtKlMD0vwEH-_zks5vK6ozgaJpZM4RaUHf
.
Ok I see.
Just out of curiosity I tried removing the default value of transparent from here
https://github.com/facebook/react-native/commit/a3a98eb1c7fa0054a236d45421393874ce8ce558
Interestingly the error still occurs for me
I just experienced this bug on RN 58.3 android. There was no apparent rhyme or reason, except that whenever I would render a TextInput
component the error would get thrown. Even if I rendered a TextInput with no props or alterations it would still crash.
I tried restarting Metro and resetting the cache but that did not work. I actually had to open Android Studio and rebuild the app, at which point it began working. Could this maybe be an issue with gradle not properly bundling dependencies or something? Seems like a long shot since I was developing for a good 4 hours without restarting anything before I experienced this issue, but I genuinely can't think of what else could cause it.
I experienced this error in RN 58.0 on devices:
Redmi Note 6 Pro - Android 8.1
Mi A2 Lite - Android 9
WAS-LX1A - Android 8
Appears sometimes by looking in Sentry, hope it helps.
Will developers fix this problem? workaround is not suitable for us!
i have this same on production
We have the same stack trace as two reported above, on React 0.59
(with DrawableContainerState.createAllFutures
on the 2nd line of the stack trace)
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875)
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158)
at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433)
at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258)
at android.view.View.computeOpaqueFlags(View.java:15718)
at android.view.View.setBackgroundDrawable(View.java:20528)
at android.view.View.setBackground(View.java:20421)
at android.view.View.<init>(View.java:5248)
at android.widget.TextView.<init>(TextView.java:826)
at android.widget.EditText.<init>(EditText.java:88)
at android.widget.EditText.<init>(EditText.java:84)
at android.widget.EditText.<init>(EditText.java:80)
at android.widget.EditText.<init>(EditText.java:76)
at com.facebook.react.views.textinput.ReactEditText.<init>(ReactEditText.java:89)
at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:102)
at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:62)
at com.facebook.react.uimanager.ViewManager.createView(ViewManager.java:47)
at com.facebook.react.uimanager.NativeViewHierarchyManager.createView(NativeViewHierarchyManager.java:256)
at com.facebook.react.uimanager.UIViewOperationQueue$CreateViewOperation.execute(UIViewOperationQueue.java:200)
at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.dispatchPendingNonBatchedOperations(UIViewOperationQueue.java:1109)
at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.doFrameGuarded(UIViewOperationQueue.java:1080)
at com.facebook.react.uimanager.GuardedFrameCallback.doFrame(GuardedFrameCallback.java:29)
at com.facebook.react.modules.core.ReactChoreographer$ReactChoreographerDispatcher.doFrame(ReactChoreographer.java:166)
at com.facebook.react.modules.core.ChoreographerCompat$FrameCallback$1.doFrame(ChoreographerCompat.java:84)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1027)
at android.view.Choreographer.doCallbacks(Choreographer.java:841)
at android.view.Choreographer.doFrame(Choreographer.java:769)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1015)
at android.os.Handler.handleCallback(Handler.java:794)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6635)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
I just got the same stacktrace as above after upgrading production version from 0.58.6 to 0.59.1 just a few hours ago. I'm afraid it will turn out to be a serious problem.
Any solution for this issue?
@sunnylqm is there a way to set underlineColorAndroid
to null, since it's set by default?
@pedrosimao @tamdao
You have to manually remove this line via some patch tool like patch-package. And if you still want to make the underline invisible, you need to set it in some xml config.
So the key point is to not set any value to underlineColorAndroid anywhere
until some hero found a way to patch this.
I got this error today
It works good before but after some build the error occurred on my device
Workaround for this issue for me are uninstall application on device then reinstall application through react-native run-android
After it the issue are gone
Btw i don't use underlineColorAndroid props, so it not work whatever i set or unset any value for that props
This happens randomly when you use some textinputs inside a scrollview. underlineColorAndroid is always used cause it's set by default.
Happened to me today as well, on Expo.
If you're on Expo, you'll need to close the expo server, your app, and the Expo app completely. And reopen them again.
Otherwise, the error would not disappear.
Happened to me, on Expo.
For some reason there were two instances of my app in the background. When I clicked on the android square button, called "Overview", to see apps in memory, I saw these two instances of my app .. when I closed them and ran the app again, it did not show this error anymore.
So, like the guys said previously, close everything and run again should be fix it
I spent 3 hours trying to figure this error out with no results, then I re-installed my app on my android emulator and the error went away.
Try 0.59.4 to see if you still encounter this crash.
@sunnylqm Still encountering this on 0.59.5.
Android: 8.0.0
Android Build: R16NW
Manufacturer: samsung
Model: SM-G955F
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875)
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158)
at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433)
at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258)
at android.view.View.computeOpaqueFlags(View.java:16791)
at android.view.View.setBackgroundDrawable(View.java:21710)
at android.view.View.setBackground(View.java:21603)
at android.view.View.<init>(View.java:5547)
at android.widget.TextView.<init>(TextView.java:1135)
at android.widget.EditText.<init>(EditText.java:107)
at android.widget.EditText.<init>(EditText.java:103)
at android.widget.EditText.<init>(EditText.java:99)
at android.widget.EditText.<init>(EditText.java:95)
at com.facebook.react.views.textinput.c.<init>
at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance
at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance
at com.facebook.react.uimanager.ViewManager.createView
at com.facebook.react.uimanager.k.a
at com.facebook.react.uimanager.aq$e.a
at com.facebook.react.uimanager.aq$h.c
at com.facebook.react.uimanager.aq$h.a
at com.facebook.react.uimanager.e.b
at com.facebook.react.modules.core.e$b.b
at com.facebook.react.modules.core.a$a$1.doFrame
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:909)
at android.view.Choreographer.doCallbacks(Choreographer.java:723)
at android.view.Choreographer.doFrame(Choreographer.java:655)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Method.java:-2)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
I have this error with a component that renders several TextInputs,
When i restart the build or the app it goes and it comes back when i rerender for the second time.
Android: 9
Phone: SAMSUNG Galaxy note 9
Model: SM-N960F/DS
react-native version "0.58.5"
Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
createAllFutures
DrawableContainer.java:875
getOpacity
DrawableContainer.java:1158
getOpacity
DrawableContainer.java:433
getOpacity
InsetDrawable.java:258
computeOpaqueFlags
View.java:18165
setBackgroundDrawable
View.java:23335
setBackground
View.java:23228
View.java:5952
TextView.java:1108
EditText.java:106
EditText.java:102
EditText.java:98
EditText.java:94
setThemedContext
ReactTextInputShadowNode.java:73
createView
UIImplementation.java:288
createView
UIManagerModule.java:449
invoke
Method.java
invoke
JavaMethodWrapper.java:372
invoke
JavaModuleWrapper.java:158
run
NativeRunnable.java
handleCallback
Handler.java:873
dispatchMessage
Handler.java:99
dispatchMessage
MessageQueueThreadHandler.java:29
loop
Looper.java:214
run
MessageQueueThreadImpl.java:192
run
Thread.java:764
I am also having the same issue on Samsung Note 8, Android version 9, and React native 0.57.0
Same issue here. React Native 0.59.0. The issue just appears randomly when using the app. Couldn't see any pattern for it to appear. Happens in both dev mode and production.
This issue has been causing our app to crash in production as well. It's a nasty bug, because it is really difficult to reproduce. We've found a promising fix for our app, and I'd like to share our findings here to hopefully save others some time & frustration.
Specs and Versions
This bug has caused our app to crash on Samsung, Google, and LG Android devices. We've had crash reports from the following Android versions:
8.0.0
8.1.0
7.1.1
Our app is running:
react-native
: 0.53.0react
: 16.2.0What causes the crash
Like others have noted in this thread, the issue seems to be triggered by rendering some combination of
TextInput
,FlatList
, andScrollView
components. In our case, we have a screen containing a singleTextInput
rendered above aFlatList
. When one of the items in theFlatList
is tapped, the app navigates to a new screen containing a form. This form's root component is aScrollView
that contains a number ofTextInput
components (along with some buttons and other custom components). Our app crashes when the user taps one of theseFlatList
items (note that it doesn't happen _every_ time).Reproducing this issue is difficult. In fact, we've been unable to do so. But we know that the crash occurs at this point in the workflow by watching our Appsee session recordings.
Because we can't reproduce the issue, we've had to rely on the crash logs from Appsee to debug it. I've copied the stack trace from the crash reports below (and omitted some noisy sections). It's more or less identical to the stack traces posted in this thread by others:
0 java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference 1 at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875) 2 at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158) 3 at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433) 4 at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258) 5 at android.view.View.computeOpaqueFlags(View.java:16900) 6 at android.view.View.setBackgroundDrawable(View.java:21824) 7 at android.view.View.setBackground(View.java:21717) 8 at android.view.View.<init>(View.java:5577) 9 at android.widget.TextView.<init>(TextView.java:1144) ... 13 at android.widget.EditText.<init>(EditText.java:96) 14 at com.facebook.react.views.textinput.ReactEditText.<init>(ReactEditText.java:91) 15 at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:91) 16 at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:61) ... 35 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Source of the problem
After reading through this thread and doing a few hours or research, I found the
underlineColorAndroid
prop handler in theReactTextInputManager.java
file:@ReactProp(name = "underlineColorAndroid", customType = "Color") public void setUnderlineColor(ReactEditText view, @Nullable Integer underlineColor) { // Drawable.mutate() can sometimes crash due to an AOSP bug: // See https://code.google.com/p/android/issues/detail?id=191754 for more info Drawable background = view.getBackground(); Drawable drawableToMutate = background.getConstantState() != null ? background.mutate() : background; if (underlineColor == null) { drawableToMutate.clearColorFilter(); } else { drawableToMutate.setColorFilter(underlineColor, PorterDuff.Mode.SRC_IN); } }
The bug report linked to in the comment contains the following stack trace:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable()' on a null object reference at android.graphics.drawable.LayerDrawable$ChildDrawable.<init>(LayerDrawable.java:1723) at android.graphics.drawable.LayerDrawable$LayerState.<init>(LayerDrawable.java:1792) at android.graphics.drawable.LayerDrawable.createConstantState(LayerDrawable.java:152) at android.graphics.drawable.LayerDrawable.mutate(LayerDrawable.java:1652)
This matches the stack trace we we are encountering in our app. I don't pretend to fully understand the underlying problem, but it seems likely that the cause of our app crashing in production is due to the
Drawable.mutate()
bug being triggered. This happens when we try to set theunderlineColorAndroid
prop on ourTextInput
component (and thus invoke theReactTextInputManager.setUnderlineColor
method).Our app was rendering a
TextInput
with the following props, one of which wasunderlineColorAndroid="transparent"
:<TextInput ref={this.handleRef} value={this.props.value} autoCorrect={false} autoCapitalize="none" underlineColorAndroid="transparent" onSubmitEditing={this.handleSubmit} onChangeText={this.props.onChangeText} onFocus={this.handleFocused} onBlur={this.handleBlur} clearButtonMode="always" />
How we fixed it
We needed to set this prop in order to remove the underline from the
TextInput
components in our app. But based on our findings, its prop handler appeared to be triggering an Android bug that caused the app to crash occasionally.Fortunately, there is another way to remove underlines from
TextInput
components on Android. You can add a line to theandroid/app/src/main/res/values/styles.xml
file:<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="android:windowExitAnimation">@android:anim/fade_out</item> <item name="android:windowBackground">@drawable/splash_screen</item> + <item name="android:editTextBackground">@android:color/transparent</item> </style> </resources>
Note that I've also seen the following suggested, but this did not remove the underlines for us:
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="android:windowExitAnimation">@android:anim/fade_out</item> <item name="android:windowBackground">@drawable/splash_screen</item> </style> + <!-- This did *not* work for us... --> + <style name="AppEditTextStyle" parent="@style/Widget.AppCompat.EditText"> + <item name="android:background">@android:color/transparent</item> + </style> </resources>
This does not address the underlying issue. It is just a workaround that involves avoiding usage of the
underlineColorAndroid
prop onTextInput
components.I cannot yet say with certainty that this actually works, because I've been unable to reproduce the issue locally. We'll be deploying this change in an update to our app in the coming weeks. After that, we'll have to wait awhile to see if it occurs anymore. I'll try to report back with our findings.
Good luck to everybody wrestling with this frustrating issue! I hope this helps.
I know how to reproduce this situation. Click back in the form as you said, and then click item in the flatlist to enter the form. Repeat about ten times, and a little faster, this error will occur. You can reproduce the error according to what I said.
@Hopding
I know how to reproduce this situation. Click back in the form as you said, and then click item in the flatlist to enter the form. Repeat about ten times, and a little faster, this error will occur. You can reproduce the error according to what I said.
@Hopding
I've removed underlineColorAndroid, but I'll reproduce it.
@react-native-bot this issue is very important
I am using RN 59.5 and also have this problem..
Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
createAllFutures
DrawableContainer.java:875
getOpacity
DrawableContainer.java:1158
getOpacity
DrawableContainer.java:433
getOpacity
InsetDrawable.java:258
computeOpaqueFlags
View.java:16594
setBackgroundDrawable
View.java:21577
setBackground
View.java:21470
View.java:5498
TextView.java:875
EditText.java:88
EditText.java:84
EditText.java:80
EditText.java:76
setThemedContext
ReactTextInputShadowNode.java:76
createView
UIImplementation.java:294
createView
UIManagerModule.java:462
invoke
Method.java
invoke
JavaMethodWrapper.java:372
invoke
JavaModuleWrapper.java:158
run
NativeRunnable.java
handleCallback
Handler.java:873
dispatchMessage
Handler.java:99
dispatchMessage
MessageQueueThreadHandler.java:29
loop
Looper.java:193
run
MessageQueueThreadImpl.java:232
run
Thread.java:764
Anyone already solved this?? I'm with this issue in RN 52, I upgraded to 56 but still the error. I tried the steps to reproduce it, but I can't. Some devices still firing this randomly.
any luck with this issue?
i get this issue RN 0.59.5
This issue has been causing our app to crash in production as well. It's a nasty bug, because it is really difficult to reproduce. We've found a promising fix for our app, and I'd like to share our findings here to hopefully save others some time & frustration.
Specs and Versions
This bug has caused our app to crash on Samsung, Google, and LG Android devices. We've had crash reports from the following Android versions:
8.0.0
8.1.0
7.1.1
Our app is running:
react-native
: 0.53.0react
: 16.2.0What causes the crash
Like others have noted in this thread, the issue seems to be triggered by rendering some combination of
TextInput
,FlatList
, andScrollView
components. In our case, we have a screen containing a singleTextInput
rendered above aFlatList
. When one of the items in theFlatList
is tapped, the app navigates to a new screen containing a form. This form's root component is aScrollView
that contains a number ofTextInput
components (along with some buttons and other custom components). Our app crashes when the user taps one of theseFlatList
items (note that it doesn't happen _every_ time).
Reproducing this issue is difficult. In fact, we've been unable to do so. But we know that the crash occurs at this point in the workflow by watching our Appsee session recordings.
Because we can't reproduce the issue, we've had to rely on the crash logs from Appsee to debug it. I've copied the stack trace from the crash reports below (and omitted some noisy sections). It's more or less identical to the stack traces posted in this thread by others:0 java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference 1 at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875) 2 at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158) 3 at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433) 4 at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258) 5 at android.view.View.computeOpaqueFlags(View.java:16900) 6 at android.view.View.setBackgroundDrawable(View.java:21824) 7 at android.view.View.setBackground(View.java:21717) 8 at android.view.View.<init>(View.java:5577) 9 at android.widget.TextView.<init>(TextView.java:1144) ... 13 at android.widget.EditText.<init>(EditText.java:96) 14 at com.facebook.react.views.textinput.ReactEditText.<init>(ReactEditText.java:91) 15 at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:91) 16 at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:61) ... 35 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Source of the problem
After reading through this thread and doing a few hours or research, I found the
underlineColorAndroid
prop handler in theReactTextInputManager.java
file:@ReactProp(name = "underlineColorAndroid", customType = "Color") public void setUnderlineColor(ReactEditText view, @Nullable Integer underlineColor) { // Drawable.mutate() can sometimes crash due to an AOSP bug: // See https://code.google.com/p/android/issues/detail?id=191754 for more info Drawable background = view.getBackground(); Drawable drawableToMutate = background.getConstantState() != null ? background.mutate() : background; if (underlineColor == null) { drawableToMutate.clearColorFilter(); } else { drawableToMutate.setColorFilter(underlineColor, PorterDuff.Mode.SRC_IN); } }
The bug report linked to in the comment contains the following stack trace:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable()' on a null object reference at android.graphics.drawable.LayerDrawable$ChildDrawable.<init>(LayerDrawable.java:1723) at android.graphics.drawable.LayerDrawable$LayerState.<init>(LayerDrawable.java:1792) at android.graphics.drawable.LayerDrawable.createConstantState(LayerDrawable.java:152) at android.graphics.drawable.LayerDrawable.mutate(LayerDrawable.java:1652)
This matches the stack trace we we are encountering in our app. I don't pretend to fully understand the underlying problem, but it seems likely that the cause of our app crashing in production is due to the
Drawable.mutate()
bug being triggered. This happens when we try to set theunderlineColorAndroid
prop on ourTextInput
component (and thus invoke theReactTextInputManager.setUnderlineColor
method).
Our app was rendering aTextInput
with the following props, one of which wasunderlineColorAndroid="transparent"
:<TextInput ref={this.handleRef} value={this.props.value} autoCorrect={false} autoCapitalize="none" underlineColorAndroid="transparent" onSubmitEditing={this.handleSubmit} onChangeText={this.props.onChangeText} onFocus={this.handleFocused} onBlur={this.handleBlur} clearButtonMode="always" />
How we fixed it
We needed to set this prop in order to remove the underline from the
TextInput
components in our app. But based on our findings, its prop handler appeared to be triggering an Android bug that caused the app to crash occasionally.
Fortunately, there is another way to remove underlines fromTextInput
components on Android. You can add a line to theandroid/app/src/main/res/values/styles.xml
file:<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="android:windowExitAnimation">@android:anim/fade_out</item> <item name="android:windowBackground">@drawable/splash_screen</item> + <item name="android:editTextBackground">@android:color/transparent</item> </style> </resources>
Note that I've also seen the following suggested, but this did not remove the underlines for us:
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="android:windowExitAnimation">@android:anim/fade_out</item> <item name="android:windowBackground">@drawable/splash_screen</item> </style> + <!-- This did *not* work for us... --> + <style name="AppEditTextStyle" parent="@style/Widget.AppCompat.EditText"> + <item name="android:background">@android:color/transparent</item> + </style> </resources>
This does not address the underlying issue. It is just a workaround that involves avoiding usage of the
underlineColorAndroid
prop onTextInput
components.
I cannot yet say with certainty that this actually works, because I've been unable to reproduce the issue locally. We'll be deploying this change in an update to our app in the coming weeks. After that, we'll have to wait awhile to see if it occurs anymore. I'll try to report back with our findings.
Good luck to everybody wrestling with this frustrating issue! I hope this helps.I know how to reproduce this situation. Click back in the form as you said, and then click item in the flatlist to enter the form. Repeat about ten times, and a little faster, this error will occur. You can reproduce the error according to what I said.
Seems like this fixes it.
For those wondering how to reproduce: We reproduced it by adding 100 <TextInput ...>
s to a <ScrollView ...>
. At that point we were able to reproduce the error with an estimated 75%-90% success rate. Enough to try out solutions. 50 fields were not enough.
@Hopding 's workaround worked for us. The proposed alternate "tint" solution (by others) does not work. The unfortunate side-effect of the workaround is that padding is removed from the text inputs.
Same here.
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875)
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158)
at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433)
at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258)
at android.view.View.computeOpaqueFlags(View.java:18188)
at android.view.View.setBackgroundDrawable(View.java:23358)
at android.view.View.setBackground(View.java:23251)
at android.view.View.(View.java:5948)
at android.widget.TextView.(TextView.java:1118)
at android.widget.EditText.(EditText.java:106)
at android.widget.EditText.(EditText.java:102)
at android.widget.EditText.(EditText.java:98)
at android.widget.EditText.(EditText.java:94)
at com.facebook.react.views.textinput.ReactEditText.(ReactEditText.java:89)
at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:105)
at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:65)
at com.facebook.react.uimanager.ViewManager.createView(ViewManager.java:47)
at com.facebook.react.uimanager.NativeViewHierarchyManager.createView(NativeViewHierarchyManager.java:256)
at com.facebook.react.uimanager.UIViewOperationQueue$CreateViewOperation.execute(UIViewOperationQueue.java:200)
at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.dispatchPendingNonBatchedOperations(UIViewOperationQueue.java:1109)
at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.doFrameGuarded(UIViewOperationQueue.java:1080)
at com.facebook.react.uimanager.GuardedFrameCallback.doFrame(GuardedFrameCallback.java:29)
at com.facebook.react.modules.core.ReactChoreographer$ReactChoreographerDispatcher.doFrame(ReactChoreographer.java:166)
at com.facebook.react.modules.core.ChoreographerCompat$FrameCallback$1.doFrame(ChoreographerCompat.java:84)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:947)
at android.view.Choreographer.doCallbacks(Choreographer.java:761)
at android.view.Choreographer.doFrame(Choreographer.java:693)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7045)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
any workaround ?
Here is a code where the error is reproduced RN 0.59.8
> import React, { Component } from 'react';
> import { StyleSheet, Text, View, TextInput, FlatList, TouchableOpacity } from 'react-native';
>
> export default class App extends Component {
> state = { Valor: [] }
> componentDidMount() {
> for (i = 0; i < 90000; i++) {
> var te = { ID: i }
> this.state.Valor.push(te)
> }
> }
>
> keyExtractor = (item, index) => item.ID.toString();
> renderList = () => {
> return (
> <FlatList
> keyExtractor={this.keyExtractor}
> data={this.state.Valor}
> renderItem={({ item }) => (
> <TouchableOpacity
> activeOpacity={0.5}
> onPress={() => alert("hola")} >
> <View style={{ flex: 1 }}>
> <Text>Muestra</Text>
> <TextInput
> underlineColorAndroid={"transparent"}
> placeholder={"Ingrese"}
> keyboardType="phone-pad"
> />
> </View>
> </TouchableOpacity>
> )}
> >
> </FlatList>
> );
> };
>
> render() {
> return (
> <View style={styles.container}>
> {this.renderList()}
> </View>
> );
> }
> }
>
> const styles = StyleSheet.create({
> container: {
> flex: 1,
> justifyContent: 'flex-start',
> alignItems: 'flex-start',
> backgroundColor: '#F5FCFF',
> },
> welcome: {
> fontSize: 20,
> textAlign: 'center',
> margin: 10,
> },
> instructions: {
> textAlign: 'center',
> color: '#333333',
> marginBottom: 5,
> }
> });
>
Video: https://www.youtube.com/watch?v=FJ6YvXrevMQ&feature=youtu.be
Solution plz.
This issue was opened on Jan 11th, 2018 and it's May 2019 now, why isn't anyone from the official team addressing it?
FYI, the workarounds aren't working.
Same here 0.59.6
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875)
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158)
at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433)
at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258)
at android.view.View.computeOpaqueFlags(View.java:18188)
at android.view.View.setBackgroundDrawable(View.java:23358)
at android.view.View.setBackground(View.java:23251)
at android.view.View.(View.java:5948)
at android.widget.TextView.(TextView.java:1118)
at android.widget.EditText.(EditText.java:106)
at android.widget.EditText.(EditText.java:102)
at android.widget.EditText.(EditText.java:98)
at android.widget.EditText.(EditText.java:94)
at com.facebook.react.views.textinput.ReactEditText.(ReactEditText.java:89)
at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:105)
at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:65)
at com.facebook.react.uimanager.ViewManager.createView(ViewManager.java:47)
at com.facebook.react.uimanager.NativeViewHierarchyManager.createView(NativeViewHierarchyManager.java:256)
at com.facebook.react.uimanager.UIViewOperationQueue$CreateViewOperation.execute(UIViewOperationQueue.java:200)
at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.dispatchPendingNonBatchedOperations(UIViewOperationQueue.java:1109)
at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.doFrameGuarded(UIViewOperationQueue.java:1080)
at com.facebook.react.uimanager.GuardedFrameCallback.doFrame(GuardedFrameCallback.java:29)
at com.facebook.react.modules.core.ReactChoreographer$ReactChoreographerDispatcher.doFrame(ReactChoreographer.java:166)
at com.facebook.react.modules.core.ChoreographerCompat$FrameCallback$1.doFrame(ChoreographerCompat.java:84)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:947)
at android.view.Choreographer.doCallbacks(Choreographer.java:761)
at android.view.Choreographer.doFrame(Choreographer.java:693)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7045)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
@knspatel Our workaround was to overlay the screen with a modal which positioned a text input box over the original along with a slight background opacity to cure the transition effect. If the y-coordinate is out of view or inaccessible, the text input box just sits right above the keyboard.
Let me recap:
The key point is to not set any value to underlineColorAndroid anywhere. But since 0.57 underlineColorAndroid is set by default, so you have to manually remove this line via some patch tool like patch-package.
And if you still want to make the underline invisible, you need to set it in some xml config.
And here's some info I found so far:
A chinese blog(can try google translate if you can not read) mentioned a very similar issue to this one. It said some custom drawable class without getConstantState
implementation can cause crash in some scenario.
I found that sometimes the textinput(ReactEditText) will be recreated (more textinputs more possibilities, kind of recycling?), and it will setBackground
again, which then goto https://github.com/aosp-mirror/platform_frameworks_base/blob/master/graphics/java/android/graphics/drawable/DrawableContainer.java#L922, where the ConstantState
is null.
The only custom drawable class I found is ReactViewBackgroundDrawable and it did not implement getConstantState
which will return null by default.
I tried to override it with some empty class and it can make some difference (this crash goes away while others emerge).
Hope this can help someone to dig more.
I found manual testing to be to be very hit and miss, so I wrote a component to automatically test some of the scenarios that people have been reporting above. You will find the component below. You just have to render it somewhere for it to do its job.
Doing this I found that you only need to add the following to the AppTheme in styles.xml as suggested by @Hopding
<item name="android:editTextBackground">@android:color/transparent</item>
Nothing else was required, and there was _no need_ to avoid setting underlineColorAndroid
, so it didn't matter that React Native now sets it by default.
The main downside of this fix is that you have to re-style your TextInputs to allow for the resulting loss of padding, and you also lose the actual underlining behaviour as well, which for us was a benefit as we always set it "transparent" to be consistent with iOS. If you need it you could make a wrapper component that watches onFocus
and onBlur
and make your own underline.
My version of React Native is 0.57.3
Here are some other things that I found using my test component:
undefined
caused the crash, but you would perhaps expect that since RN now defaults it to "transparent"displayForMs: 0
suggesting that it only occurs when the TextInputs have only recently been created.If you don't want to hang around while testing you can capture the output of adb logcat
and look for the console messages produced by the component and the crash report.
Here is my test component should you wish to use it. The test parameters are set to cause a crash typically in under 30 seconds for me.
/**
* A test component to reproduce the crash reported at
* https://github.com/facebook/react-native/issues/17530
*/
import * as React from "react";
import { View, ScrollView, TextInput, Text, StyleSheet } from "react-native";
// These are the test parameters
const params = {
underlineColors: ["red", undefined, "transparent", "rgba(0, 0, 0, 0)"], // The colors to test
numberOfInputs: 100, // How many TextInput to render at a time
focusIntervalMs: 200, // How often to change focus between them
displayForMs: 3000, // How long to display them (set to 0 for indefinite)
delayDisplayForMs: 10, // How long to delay between displays
withScrollView: false // Whether to use a ScrollView
};
const testText = index =>
`Testing underlineColor = ${params.underlineColors[index] || "undefined"}`;
class AndroidTextInputTest extends React.Component{
state = {
underlineColorIndex: 0,
showInputs: true,
startKey: 0
};
mounted = false;
focusInterval = undefined;
textInputRefs = undefined;
focussedInputIndex = 0;
componentDidMount() {
console.log(`Testing with params = `, JSON.stringify(params));
this.mounted = true;
setTimeout(this._showInputs, params.delayDisplayForMs);
setInterval(this._focusAnInput, params.focusIntervalMs);
}
componentWillUnmount() {
clearInterval(this.focusInterval);
this.mounted = false;
}
_focusAnInput = () => {
if (this.mounted && this.textInputRefs) {
if (this.focussedInputIndex >= this.textInputRefs.length) {
this.focussedInputIndex = 0;
}
const textInputRef = this.textInputRefs[this.focussedInputIndex];
const textInput = this.refs[textInputRef];
if (textInput) {
this.focussedInputIndex++;
this.refs[textInputRef].focus();
}
}
};
_showInputs = () => {
if (this.mounted) {
console.log(testText(this.state.underlineColorIndex));
this.setState({ showInputs: true });
if (params.displayForMs) {
setTimeout(this._unshowInputs, params.displayForMs);
}
}
};
_unshowInputs = () => {
this.focussedInputIndex = 0;
this.textInputRefs = undefined;
if (this.mounted) {
let next = this.state.underlineColorIndex + 1;
if (next === params.underlineColors.length) {
next = 0;
}
this.setState({
underlineColorIndex: next,
showInputs: false,
startKey: this.state.startKey + params.numberOfInputs
});
setTimeout(this._showInputs, params.delayDisplayForMs);
}
};
render() {
const textInputs = [];
const { underlineColorIndex } = this.state;
const underlineColor = params.underlineColors[underlineColorIndex];
const refs = [];
if (this.state.showInputs) {
for (let i = 0; i < params.numberOfInputs; i++) {
const key = this.state.startKey + i + "";
refs.push(key);
textInputs.push(
<TextInput
ref={key}
key={key}
placeholder={key}
underlineColorAndroid={underlineColor}
style={styles.textInput}
/>
);
}
if (!this.textInputRefs) {
this.textInputRefs = refs;
}
}
return (
<View style={styles.mainView}>
<Text>{testText(underlineColorIndex)}</Text>
{params.withScrollView ? (
<React.Fragment>
<Text>With ScrollView</Text>
<ScrollView>{textInputs}</ScrollView>
</React.Fragment>
) : (
<React.Fragment>{textInputs}</React.Fragment>
)}
</View>
);
}
}
const styles = StyleSheet.create({
mainView: {
flex: 1,
alignItems: "center"
},
textInput: {
backgroundColor: "white",
margin: 5,
width: 300
}
});
export default AndroidTextInputTest;
For all those looking for a solution I can also confirm that setting
FYI: We're using React-Native Paper and their TextInput component and we were able to safely set <item name="android:editTextBackground">@android:color/transparent</item>
without any effect to the RN-Paper TextInput and haven't experienced the crash anymore since then.
Seeing in production on 0.59.9
.
Samsung Galaxy S7 Edge
Android 8.0
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures + 875(DrawableContainer.java:875)
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity + 1158(DrawableContainer.java:1158)
at android.graphics.drawable.DrawableContainer.getOpacity + 433(DrawableContainer.java:433)
at android.graphics.drawable.InsetDrawable.getOpacity + 258(InsetDrawable.java:258)
at android.view.View.computeOpaqueFlags + 16809(View.java:16809)
at android.view.View.setBackgroundDrawable + 21728(View.java:21728)
at android.view.View.setBackground + 21621(View.java:21621)
at android.view.View.<init> + 5553(View.java:5553)
at android.widget.TextView.<init> + 1135(TextView.java:1135)
at android.widget.EditText.<init> + 107(EditText.java:107)
at android.widget.EditText.<init> + 103(EditText.java:103)
at android.widget.EditText.<init> + 99(EditText.java:99)
at android.widget.EditText.<init> + 95(EditText.java:95)
at com.facebook.react.views.textinput.ReactTextInputShadowNode.setThemedContext + 76(ReactTextInputShadowNode.java:76)
at com.facebook.react.uimanager.UIImplementation.createView + 294(UIImplementation.java:294)
at com.facebook.react.uimanager.UIManagerModule.createView + 462(UIManagerModule.java:462)
at java.lang.reflect.Method.invoke(Method.java)
at com.facebook.react.bridge.JavaMethodWrapper.invoke + 372(JavaMethodWrapper.java:372)
at com.facebook.react.bridge.JavaModuleWrapper.invoke + 158(JavaModuleWrapper.java:158)
at com.facebook.react.bridge.queue.NativeRunnable.run(NativeRunnable.java)
at android.os.Handler.handleCallback + 789(Handler.java:789)
at android.os.Handler.dispatchMessage + 98(Handler.java:98)
at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage + 29(MessageQueueThreadHandler.java:29)
at android.os.Looper.loop + 164(Looper.java:164)
at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run + 232(MessageQueueThreadImpl.java:232)
at java.lang.Thread.run + 764(Thread.java:764)
Changing this:
state = {
data: []
}
to this:
constructor(props) {
super(props);
this.state = {
data: []
};
}
fixed the issue for me. Not sure why because setting state as a class variable should be okay? Anyone?
@wbodron No, that's unrelated. The crash is random so you may think it's gone but actually not. And the key point i've explained above https://github.com/facebook/react-native/issues/17530#issuecomment-500865260
cc @cpojer @shergin @sahrens
Delete build folder from android.
Your_Project > android > app > build
After deleting it, run react-native run-android
should work fine.
Worked for me :D
I already tried this and removing underlineColorAndroid but still with the issue. Anyone with another workaround?
This issue has been causing our app to crash in production as well. It's a nasty bug, because it is really difficult to reproduce. We've found a promising fix for our app, and I'd like to share our findings here to hopefully save others some time & frustration.
Specs and Versions
This bug has caused our app to crash on Samsung, Google, and LG Android devices. We've had crash reports from the following Android versions:
8.0.0
8.1.0
7.1.1
Our app is running:
react-native
: 0.53.0react
: 16.2.0What causes the crash
Like others have noted in this thread, the issue seems to be triggered by rendering some combination of
TextInput
,FlatList
, andScrollView
components. In our case, we have a screen containing a singleTextInput
rendered above aFlatList
. When one of the items in theFlatList
is tapped, the app navigates to a new screen containing a form. This form's root component is aScrollView
that contains a number ofTextInput
components (along with some buttons and other custom components). Our app crashes when the user taps one of theseFlatList
items (note that it doesn't happen _every_ time).
Reproducing this issue is difficult. In fact, we've been unable to do so. But we know that the crash occurs at this point in the workflow by watching our Appsee session recordings.
Because we can't reproduce the issue, we've had to rely on the crash logs from Appsee to debug it. I've copied the stack trace from the crash reports below (and omitted some noisy sections). It's more or less identical to the stack traces posted in this thread by others:0 java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference 1 at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875) 2 at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158) 3 at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433) 4 at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258) 5 at android.view.View.computeOpaqueFlags(View.java:16900) 6 at android.view.View.setBackgroundDrawable(View.java:21824) 7 at android.view.View.setBackground(View.java:21717) 8 at android.view.View.<init>(View.java:5577) 9 at android.widget.TextView.<init>(TextView.java:1144) ... 13 at android.widget.EditText.<init>(EditText.java:96) 14 at com.facebook.react.views.textinput.ReactEditText.<init>(ReactEditText.java:91) 15 at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:91) 16 at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance(ReactTextInputManager.java:61) ... 35 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Source of the problem
After reading through this thread and doing a few hours or research, I found the
underlineColorAndroid
prop handler in theReactTextInputManager.java
file:@ReactProp(name = "underlineColorAndroid", customType = "Color") public void setUnderlineColor(ReactEditText view, @Nullable Integer underlineColor) { // Drawable.mutate() can sometimes crash due to an AOSP bug: // See https://code.google.com/p/android/issues/detail?id=191754 for more info Drawable background = view.getBackground(); Drawable drawableToMutate = background.getConstantState() != null ? background.mutate() : background; if (underlineColor == null) { drawableToMutate.clearColorFilter(); } else { drawableToMutate.setColorFilter(underlineColor, PorterDuff.Mode.SRC_IN); } }
The bug report linked to in the comment contains the following stack trace:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable()' on a null object reference at android.graphics.drawable.LayerDrawable$ChildDrawable.<init>(LayerDrawable.java:1723) at android.graphics.drawable.LayerDrawable$LayerState.<init>(LayerDrawable.java:1792) at android.graphics.drawable.LayerDrawable.createConstantState(LayerDrawable.java:152) at android.graphics.drawable.LayerDrawable.mutate(LayerDrawable.java:1652)
This matches the stack trace we we are encountering in our app. I don't pretend to fully understand the underlying problem, but it seems likely that the cause of our app crashing in production is due to the
Drawable.mutate()
bug being triggered. This happens when we try to set theunderlineColorAndroid
prop on ourTextInput
component (and thus invoke theReactTextInputManager.setUnderlineColor
method).
Our app was rendering aTextInput
with the following props, one of which wasunderlineColorAndroid="transparent"
:<TextInput ref={this.handleRef} value={this.props.value} autoCorrect={false} autoCapitalize="none" underlineColorAndroid="transparent" onSubmitEditing={this.handleSubmit} onChangeText={this.props.onChangeText} onFocus={this.handleFocused} onBlur={this.handleBlur} clearButtonMode="always" />
How we fixed it
We needed to set this prop in order to remove the underline from the
TextInput
components in our app. But based on our findings, its prop handler appeared to be triggering an Android bug that caused the app to crash occasionally.
Fortunately, there is another way to remove underlines fromTextInput
components on Android. You can add a line to theandroid/app/src/main/res/values/styles.xml
file:<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="android:windowExitAnimation">@android:anim/fade_out</item> <item name="android:windowBackground">@drawable/splash_screen</item> + <item name="android:editTextBackground">@android:color/transparent</item> </style> </resources>
Note that I've also seen the following suggested, but this did not remove the underlines for us:
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="android:windowExitAnimation">@android:anim/fade_out</item> <item name="android:windowBackground">@drawable/splash_screen</item> </style> + <!-- This did *not* work for us... --> + <style name="AppEditTextStyle" parent="@style/Widget.AppCompat.EditText"> + <item name="android:background">@android:color/transparent</item> + </style> </resources>
This does not address the underlying issue. It is just a workaround that involves avoiding usage of the
underlineColorAndroid
prop onTextInput
components.
I cannot yet say with certainty that this actually works, because I've been unable to reproduce the issue locally. We'll be deploying this change in an update to our app in the coming weeks. After that, we'll have to wait awhile to see if it occurs anymore. I'll try to report back with our findings.
Good luck to everybody wrestling with this frustrating issue! I hope this helps.I know how to reproduce this situation. Click back in the form as you said, and then click item in the flatlist to enter the form. Repeat about ten times, and a little faster, this error will occur. You can reproduce the error according to what I said.
what can i do? i m facing this issue too!
same here. Facing it in production
@jake41 I tried restart it and it worked, have u try restart it? I face this issue after I update my expo cli, I think is the version problem.
@agrass I will try your method. Looks promising.
But, my app crashes very rare with this cause. Does this issue make the app crash every time? or sometimes?
DAU of our app is around 8k, and this happens approximately once a day. So, it's negligible, but I hope to cure the crash.
Did anyone find a proper working fix for it? It occurs very rarely and only in the component where there is a text field.
The issue still persists with React Native 0.60
React Native: 0.59.8
Android: 8.1.0
Device: Redmi 5 Plus
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures + 875(DrawableContainer.java:875)
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity + 1158(DrawableContainer.java:1158)
at android.graphics.drawable.DrawableContainer.getOpacity + 433(DrawableContainer.java:433)
at android.graphics.drawable.InsetDrawable.getOpacity + 258(InsetDrawable.java:258)
at android.view.View.computeOpaqueFlags + 15726(View.java:15726)
at android.view.View.setBackgroundDrawable + 20536(View.java:20536)
at android.view.View.setBackground + 20429(View.java:20429)
at android.view.View.(View.java:5256)
at android.widget.TextView.(TextView.java:826)
at android.widget.EditText.(EditText.java:88)
at android.widget.EditText.(EditText.java:84)
at android.widget.EditText.(EditText.java:80)
at android.widget.EditText.(EditText.java:76)
at com.facebook.react.views.textinput.ReactEditText.(ReactEditText.java:89)
at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance + 105(ReactTextInputManager.java:105)
at com.facebook.react.views.textinput.ReactTextInputManager.createViewInstance + 65(ReactTextInputManager.java:65)
at com.facebook.react.uimanager.ViewManager.createView + 47(ViewManager.java:47)
at com.facebook.react.uimanager.NativeViewHierarchyManager.createView + 256(NativeViewHierarchyManager.java:256)
at com.facebook.react.uimanager.UIViewOperationQueue$CreateViewOperation.execute + 200(UIViewOperationQueue.java:200)
at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.dispatchPendingNonBatchedOperations + 1109(UIViewOperationQueue.java:1109)
at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.doFrameGuarded + 1080(UIViewOperationQueue.java:1080)
at com.facebook.react.uimanager.GuardedFrameCallback.doFrame + 29(GuardedFrameCallback.java:29)
at com.facebook.react.modules.core.ReactChoreographer$ReactChoreographerDispatcher.doFrame + 166(ReactChoreographer.java:166)
at com.facebook.react.modules.core.ChoreographerCompat$FrameCallback$1.doFrame + 84(ChoreographerCompat.java:84)
at android.view.Choreographer$CallbackRecord.run + 1027(Choreographer.java:1027)
at android.view.Choreographer.doCallbacks + 841(Choreographer.java:841)
at android.view.Choreographer.doFrame + 769(Choreographer.java:769)
at android.view.Choreographer$FrameDisplayEventReceiver.run + 1015(Choreographer.java:1015)
at android.os.Handler.handleCallback + 794(Handler.java:794)
at android.os.Handler.dispatchMessage + 99(Handler.java:99)
at android.os.Looper.loop + 176(Looper.java:176)
at android.app.ActivityThread.main + 6651(ActivityThread.java:6651)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run + 547(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main + 824(ZygoteInit.java:824)
Have a same issue here
RN : 0.59.9
Device : Pixel 2
Android : 9.0
Se for uma tela de formulário, pode ser que esteja esperando definir valores nos inputs, funcionou para mim.
I found a solution. Not sure if it's a long term one, but this will let you guys work until a permanent solution is found.
Just clear your cash: npm start -- --reset-cache
And restart the project.
It worked for me.
FYI, Ididn't eject my project yet.
My dependencies:
"devDependencies": {
"@types/react": "^16.8.23",
"@types/react-native": "^0.57.65",
"babel-preset-expo": "^6.0.0",
"typescript": "^3.4.5"
},
ExpoKit (SDK 34) user weighing in here. I've had this issue on all versions of ExpoKit, including the latest. I've tried applying these fixes, with some modifications, and, so far, so good.
The style change ended up being a little different @Hopding's - basically the opposite worked for me. I changed the ExponentEditText
style in styles.xml as such:
<style name="ExponentEditText" parent="@android:style/Widget.EditText">
<item name="android:padding">0dp</item>
<item name="android:textColorHint">#c8c8c8</item>
<item name="android:textColor">#000000</item>
<item name="android:background">@android:color/transparent</item>
</style>
as the change to android:editTextBackground
did not work (maybe it has something to do with this ExponentEditText
style already being there). Interestingly, I did not have to patch away the default prop setting the underlineColorAndroid
to transparent
. I did have the padding issue; however I felt like it actually was an improvement, as I no longer had to deal with the intrinsic padding of the TextInput when it is empty and I'm trying to position other components close to it.
Previously, I was able to reliably trigger the error through a diagnostic button I added to our app that added 500 TextInputs to a SectionList. I'd say it triggers 60% of the time on the first try, 90% by the second, and 100% by the third in my experience. Tried it at least 10 times without an error after I made the change.
Have a same issue here
RN : 0.55.4
Device : MI 8 Lite
Android : 8.1.0
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875)
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158)
at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433)
at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258)
at android.view.View.computeOpaqueFlags(View.java:15748)
at android.view.View.setBackgroundDrawable(View.java:20558)
at android.view.View.setBackground(View.java:20451)
at android.view.View.
at android.widget.TextView.
at android.widget.EditText.
at android.widget.EditText.
at android.widget.EditText.
at android.widget.EditText.
at com.facebook.react.views.textinput.ReactTextInputShadowNode.setThemedContext(ReactTextInputShadowNode.java:80)
at com.facebook.react.uimanager.UIImplementation.createView(UIImplementation.java:282)
at com.facebook.react.uimanager.UIManagerModule.createView(UIManagerModule.java:366)
at java.lang.reflect.Method.invoke(Method.java)
at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372)
at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:160)
at com.facebook.react.bridge.queue.NativeRunnable.run(NativeRunnable.java)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)
at android.os.Looper.loop(Looper.java:164)
at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:192)
at java.lang.Thread.run(Thread.java:764)
Fatal Exception: java.lang.NullPointerException
Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
vivo 1804
Android Version: 9
Happening for me. React Native version 0.60.4 running on Android 9. Very intermittent and rare, though.
Happening for me. React Native version 0.60.4 running on Android 9. Very intermittent and rare, though.
Same with me too...
Same here, React Native 0.60.4 on Android 9
I use React Native with Expo, and had this problem this morning.
I tried first to put this line in my styles.xml AppTheme like this
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:editTextBackground">@android:color/transparent</item>
</style>
It didn't work, so i searched for another place, and finally put it there:
<style name="Theme.ReactNative.AppCompat.Light.NoActionBar.FullScreen"
parent="@style/Theme.ReactNative.AppCompat.Light">
<item name="android:windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:editTextBackground">@android:color/transparent</item>
</style>
Seems to work perfectly fine now
This crash is so random. Same stack trace, v0.60.4. Same error. Is there a solution? Someone suggested deleting the build folder but I do not see what that has to do with a null pointer? The solution always seem to be a rebuild/re-run
@armagedan @jacobbeasley et al the problem _is_ intermittent so you may wish to try the drop-in component provided in my comment above to reproduce it. That comment also provides an analysis of the problem and a solution that works for me and many others.
@wxjer i try clear app data on setting and it working! can you try it
Same here, React Native 0.60.4 on Android 9 and Android 8
Any solution?
In case anyone has a good eye for Android debugging here's our sentry error that just reported.
react-native 0.60.4
https://sentry.io/share/issue/e0c581e2e99a4ca48199647b8bd3f497/
Same here, React Native 0.60.5 on Android 9
Hello! We solved this by removing the underlineColorAndroid property from our TextInput and add this line to styles.xml inside (android/src/main/res/values/styles.xml)
<item name="android:editTextBackground">@android:color/transparent</item>
Is this a bug report?
yes
Have you read the Contributing Guidelines?
yes, I am sorry that I cant offer more information about this exception except for this stack trace because the crash report was collected from google analytics, I have no idea to reappear this exception.
Environment
Environment:
OS: macOS Sierra 10.12.6
Node: 8.4.0
Yarn: 0.27.5
npm: 5.4.0
Android Studio: 3.0Packages: (wanted => installed)
react-native: 0.51.0 => 0.51.0
react: 16.0.0-alpha.12 => 16.0.0-alpha.12Target Platform: Android (7.1.1)
mobile:MIX 2
android:7.1.1
java.lang.NullPointerException:
tempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference at
android.graphics.drawable.DrawableContainer$DrawableContainerState.getChild(DrawableContainer.java:888) at
android.graphics.drawable.DrawableContainer.selectDrawable(DrawableContainer.java:466) at
android.graphics.drawable.StateListDrawable.onStateChange(StateListDrawable.java:104) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.graphics.drawable.DrawableWrapper.onStateChange(DrawableWrapper.java:331) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.graphics.drawable.LayerDrawable.onStateChange(LayerDrawable.java:1488) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.view.View.drawableStateChanged(View.java:18002) at
android.widget.TextView.drawableStateChanged(TextView.java:4097) at
android.view.View.refreshDrawableState(View.java:18071) at
android.view.View.setPressed(View.java:8543) at
android.view.View.setPressed(View.java:8521) at
android.view.View.onTouchEvent(View.java:11218) at
android.widget.TextView.onTouchEvent(TextView.java:8467) at
com.facebook.react.views.textinput.ReactEditText.onTouchEvent(ReactEditText.java:150)
react-native 0.60.4 me too
Started running into this crash recently, RN 0.60.5, mainly on Android 8 / 9 (possibly 10 too, haven't tested that extensively yet).
https://github.com/facebook/react-native/issues/17530#issuecomment-504044357 seems to do the trick for me. Typically, the crash would present itself within the first ~5 iterations that the test component goes through. After adding that one line it ran for ~200 iterations without a crash before I stopped it.
edit: Using the testing component, I am able to reliably reproduce this on Android 6 as well, though again the suggested fix seems to solve the issue.
Same here on RN 0.61
HI guys, @diegotsi solution worked for me. I have never seen the crash since I use his solution
This issue does still exist and it broke my app - everything was working fine than I added a fetch call and now even when I comment it out I cant get the app running again :cry: I am using Expo btw
EDIT: I fixxed my issue for expo by reinstalling the expo app on my device
Ran into this error as well (RN: 0.61.1, Android 10 api 29). 'npm start --reset-cache' appeared to fix.
@johnbowdenatfacet you may wish to try the drop-in test component provided in my comment above to confirm the fix.
Same issue.
React-Native 0.59.10
Android
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875)
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158)
at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433)
at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258)
Same issue.
Hello! We solved this by removing the underlineColorAndroid property from our TextInput and add this line to styles.xml inside (android/src/main/res/values/styles.xml)
<item name="android:editTextBackground">@android:color/transparent</item>
Solved my issue, Thank you very much.
I just ran (react-native run-android), that solved the problem with me
Same issue on 0.61.3
I am still facing the issue. We have some users reporting Android app crashes, but it happens so randomly that I can't reproduce.
+1, happend for me too
@pedrosimao you may wish to try the drop-in test component provided in my comment above to reliably reproduce the fault. That comment also points to a fix for the problem.
I narrowed down the problem its in input for me which is imported from native base.
Updated:
I restarted my PC and phone and then run again, It worked like charm :)
I had this as well. I have solved the issue by re-running expo via expo r -c
Reporting same issue for RN 0.59.10
I found manual testing to be to be very hit and miss, so I wrote a component to automatically test some of the scenarios that people have been reporting above. You will find the component below. You just have to render it somewhere for it to do its job.
Doing this I found that you only need to add the following to the AppTheme in styles.xml as suggested by @Hopding
<item name="android:editTextBackground">@android:color/transparent</item>
Nothing else was required, and there was _no need_ to avoid setting
underlineColorAndroid
, so it didn't matter that React Native now sets it by default.The main downside of this fix is that you have to re-style your TextInputs to allow for the resulting loss of padding, and you also lose the actual underlining behaviour as well, which for us was a benefit as we always set it "transparent" to be consistent with iOS. If you need it you could make a wrapper component that watches
onFocus
andonBlur
and make your own underline.My version of React Native is 0.57.3
Here are some other things that I found using my test component:
- I couldn't cause the crash at all on my low-spec android tablet device. It was quite easy to reproduce however on my Samsung S6 Edge phone running Android 7. My guess is that there is a race condition that needs a faster device to provoke it.
- Scrolling the text inputs made no difference, and I could easily reproduce the problem without even using a ScrollView.
- Entering text wasn't necessary. Simply changing the focus was enough to cause the crash.
- It made no difference what color you set the underline to, even
undefined
caused the crash, but you would perhaps expect that since RN now defaults it to "transparent"- Having a fair number of TextInputs showing at once made a difference with the crash happening quicker with 100, than just 10 on the screen.
- I couldn't reproduce the crash with
displayForMs: 0
suggesting that it only occurs when the TextInputs have only recently been created.If you don't want to hang around while testing you can capture the output of
adb logcat
and look for the console messages produced by the component and the crash report.Here is my test component should you wish to use it. The test parameters are set to cause a crash typically in under 30 seconds for me.
/** * A test component to reproduce the crash reported at * https://github.com/facebook/react-native/issues/17530 */ import * as React from "react"; import { View, ScrollView, TextInput, Text, StyleSheet } from "react-native"; // These are the test parameters const params = { underlineColors: ["red", undefined, "transparent", "rgba(0, 0, 0, 0)"], // The colors to test numberOfInputs: 100, // How many TextInput to render at a time focusIntervalMs: 200, // How often to change focus between them displayForMs: 3000, // How long to display them (set to 0 for indefinite) delayDisplayForMs: 10, // How long to delay between displays withScrollView: false // Whether to use a ScrollView }; const testText = index => `Testing underlineColor = ${params.underlineColors[index] || "undefined"}`; class AndroidTextInputTest extends React.Component{ state = { underlineColorIndex: 0, showInputs: true, startKey: 0 }; mounted = false; focusInterval = undefined; textInputRefs = undefined; focussedInputIndex = 0; componentDidMount() { console.log(`Testing with params = `, JSON.stringify(params)); this.mounted = true; setTimeout(this._showInputs, params.delayDisplayForMs); setInterval(this._focusAnInput, params.focusIntervalMs); } componentWillUnmount() { clearInterval(this.focusInterval); this.mounted = false; } _focusAnInput = () => { if (this.mounted && this.textInputRefs) { if (this.focussedInputIndex >= this.textInputRefs.length) { this.focussedInputIndex = 0; } const textInputRef = this.textInputRefs[this.focussedInputIndex]; const textInput = this.refs[textInputRef]; if (textInput) { this.focussedInputIndex++; this.refs[textInputRef].focus(); } } }; _showInputs = () => { if (this.mounted) { console.log(testText(this.state.underlineColorIndex)); this.setState({ showInputs: true }); if (params.displayForMs) { setTimeout(this._unshowInputs, params.displayForMs); } } }; _unshowInputs = () => { this.focussedInputIndex = 0; this.textInputRefs = undefined; if (this.mounted) { let next = this.state.underlineColorIndex + 1; if (next === params.underlineColors.length) { next = 0; } this.setState({ underlineColorIndex: next, showInputs: false, startKey: this.state.startKey + params.numberOfInputs }); setTimeout(this._showInputs, params.delayDisplayForMs); } }; render() { const textInputs = []; const { underlineColorIndex } = this.state; const underlineColor = params.underlineColors[underlineColorIndex]; const refs = []; if (this.state.showInputs) { for (let i = 0; i < params.numberOfInputs; i++) { const key = this.state.startKey + i + ""; refs.push(key); textInputs.push( <TextInput ref={key} key={key} placeholder={key} underlineColorAndroid={underlineColor} style={styles.textInput} /> ); } if (!this.textInputRefs) { this.textInputRefs = refs; } } return ( <View style={styles.mainView}> <Text>{testText(underlineColorIndex)}</Text> {params.withScrollView ? ( <React.Fragment> <Text>With ScrollView</Text> <ScrollView>{textInputs}</ScrollView> </React.Fragment> ) : ( <React.Fragment>{textInputs}</React.Fragment> )} </View> ); } } const styles = StyleSheet.create({ mainView: { flex: 1, alignItems: "center" }, textInput: { backgroundColor: "white", margin: 5, width: 300 } }); export default AndroidTextInputTest;
Tried this but Keyboard was not showing up on TextInputs. Any solutions?
Thanks for trying my component @saketkumar.
I can't recall if the keyboard needs to appear for this test, though I would expect it to appear when the text input is focussed. Are you using an actual device or an emulator?
Could you see the cursor appearing in the text inputs as they were focussed, and was the component able to reproduce the crash for you?
The same
Happens in react 0.59 on Variety of Android phones.
Occurs randomly in components with TextInput
nested within Flatlist
Tried to set underlineColorAndroid={null}
atrribute on TextInput
as discussed in this thread but the error persists
I had to restart my phone and reinstall EXPO for it to get fixed. If that won't work for you I would try clearing your cache and clearing cache of the EXPO APP itself.
Got no Idea how that ERROR occured in the first place. I could not recreate it nor figure out how to prevent it from that happening again.
It just started and no matter what I changed in my code it didn't fix it. It is certanly the issue with EXPO APP because I see the ERROR in the APP but not in my console or any where else.
+1 Error still exist in RN 0.59.9. reported from firebase crashlytics
first one to get this error on RN 0.61 ?
Getting same error in RN 0.61, @diegotsi 's solution fixed it though.
This is a serious problem, as it first happened to me in pre-production environment, and I would never have been able to trace it without crashlytics, as erratic behaviour makes it difficult to reproduce.
Is this a bug report?
yes
Have you read the Contributing Guidelines?
yes, I am sorry that I cant offer more information about this exception except for this stack trace because the crash report was collected from google analytics, I have no idea to reappear this exception.
Environment
Environment:
OS: macOS Sierra 10.12.6
Node: 8.4.0
Yarn: 0.27.5
npm: 5.4.0
Android Studio: 3.0Packages: (wanted => installed)
react-native: 0.51.0 => 0.51.0
react: 16.0.0-alpha.12 => 16.0.0-alpha.12Target Platform: Android (7.1.1)
mobile:MIX 2
android:7.1.1
java.lang.NullPointerException:
tempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference at
android.graphics.drawable.DrawableContainer$DrawableContainerState.getChild(DrawableContainer.java:888) at
android.graphics.drawable.DrawableContainer.selectDrawable(DrawableContainer.java:466) at
android.graphics.drawable.StateListDrawable.onStateChange(StateListDrawable.java:104) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.graphics.drawable.DrawableWrapper.onStateChange(DrawableWrapper.java:331) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.graphics.drawable.LayerDrawable.onStateChange(LayerDrawable.java:1488) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.view.View.drawableStateChanged(View.java:18002) at
android.widget.TextView.drawableStateChanged(TextView.java:4097) at
android.view.View.refreshDrawableState(View.java:18071) at
android.view.View.setPressed(View.java:8543) at
android.view.View.setPressed(View.java:8521) at
android.view.View.onTouchEvent(View.java:11218) at
android.widget.TextView.onTouchEvent(TextView.java:8467) at
com.facebook.react.views.textinput.ReactEditText.onTouchEvent(ReactEditText.java:150)
Is this a bug report?
yes
Have you read the Contributing Guidelines?
yes, I am sorry that I cant offer more information about this exception except for this stack trace because the crash report was collected from google analytics, I have no idea to reappear this exception.
Environment
Environment:
OS: macOS Sierra 10.12.6
Node: 8.4.0
Yarn: 0.27.5
npm: 5.4.0
Android Studio: 3.0Packages: (wanted => installed)
react-native: 0.51.0 => 0.51.0
react: 16.0.0-alpha.12 => 16.0.0-alpha.12Target Platform: Android (7.1.1)
mobile:MIX 2
android:7.1.1
java.lang.NullPointerException:
tempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference at
android.graphics.drawable.DrawableContainer$DrawableContainerState.getChild(DrawableContainer.java:888) at
android.graphics.drawable.DrawableContainer.selectDrawable(DrawableContainer.java:466) at
android.graphics.drawable.StateListDrawable.onStateChange(StateListDrawable.java:104) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.graphics.drawable.DrawableWrapper.onStateChange(DrawableWrapper.java:331) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.graphics.drawable.LayerDrawable.onStateChange(LayerDrawable.java:1488) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.view.View.drawableStateChanged(View.java:18002) at
android.widget.TextView.drawableStateChanged(TextView.java:4097) at
android.view.View.refreshDrawableState(View.java:18071) at
android.view.View.setPressed(View.java:8543) at
android.view.View.setPressed(View.java:8521) at
android.view.View.onTouchEvent(View.java:11218) at
android.widget.TextView.onTouchEvent(TextView.java:8467) at
com.facebook.react.views.textinput.ReactEditText.onTouchEvent(ReactEditText.java:150)
This happens when I'm changing something in style like deleting justifyContent or smthng like this and restarting app works for temporarily.
@cinocai , @Sargnec et al, this comments thread is getting so long that I think folks are missing the testing component I posted above
Several people above have used it to successfully reproduce this problem, and verify the solution, which is also mentioned in that comment.
@glenn-axsy : Great work with testing component, was very helpful understanding the issue better.
But I am struggling to find a solution.
As you have suggested upon setting displayForMs: 0
it does not crash. If I am not wrong, by doing so, the 100
TextInputs never unmounts(only updates), no new ones either.
I tried setting displayForMs: 3000
itself and made 2 other changes, which kept all the 100
mounted(only updating) on each set state.
Changes
${i}
;if (this.state.showInputs) {
inside render.
code
/**
* A test component to reproduce the crash reported at
* https://github.com/facebook/react-native/issues/17530
*/
import * as React from 'react';
import { View, ScrollView, TextInput, Text, StyleSheet } from 'react-native';
// These are the test parameters
const params = {
underlineColors: ['red', undefined, 'transparent', 'rgba(0, 0, 0, 0)'], // The colors to test
numberOfInputs: 100, // How many TextInput to render at a time
focusIntervalMs: 200, // How often to change focus between them
displayForMs: 3000, // How long to display them (set to 0 for indefinite)
delayDisplayForMs: 10, // How long to delay between displays
withScrollView: false, // Whether to use a ScrollView
};
const testText = index =>
`Testing underlineColor = ${params.underlineColors[index] || 'undefined'}`;
class AndroidTextInputTest extends React.Component {
state = {
underlineColorIndex: 0,
showInputs: true,
startKey: 0,
};
mounted = false;
focusInterval = undefined;
textInputRefs = undefined;
focussedInputIndex = 0;
componentDidMount() {
console.log('Testing with params = ', JSON.stringify(params));
this.mounted = true;
setTimeout(this._showInputs, params.delayDisplayForMs);
setInterval(this._focusAnInput, params.focusIntervalMs);
}
componentWillUnmount() {
clearInterval(this.focusInterval);
this.mounted = false;
}
_focusAnInput = () => {
if (this.mounted && this.textInputRefs) {
if (this.focussedInputIndex >= this.textInputRefs.length) {
this.focussedInputIndex = 0;
}
const textInputRef = this.textInputRefs[this.focussedInputIndex];
const textInput = this.refs[textInputRef];
if (textInput) {
this.focussedInputIndex++;
this.refs[textInputRef].focus();
}
}
};
_showInputs = () => {
if (this.mounted) {
console.log(testText(this.state.underlineColorIndex));
this.setState({ showInputs: true });
if (params.displayForMs) {
setTimeout(this._unshowInputs, params.displayForMs);
}
}
};
_unshowInputs = () => {
this.focussedInputIndex = 0;
this.textInputRefs = undefined;
if (this.mounted) {
let next = this.state.underlineColorIndex + 1;
if (next === params.underlineColors.length) {
next = 0;
}
this.setState({
underlineColorIndex: next,
showInputs: false,
startKey: this.state.startKey + params.numberOfInputs,
});
setTimeout(this._showInputs, params.delayDisplayForMs);
}
};
render() {
const textInputs = [];
const { underlineColorIndex } = this.state;
const underlineColor = params.underlineColors[underlineColorIndex];
const refs = [];
// CHANGE 2
// if (this.state.showInputs) {
for (let i = 0; i < params.numberOfInputs; i++) {
const key = `${i}`; // CHANGE 1
refs.push(key);
textInputs.push(
Both the changes made sure calling _showInputs
and _unshowInputs
will neither remount the TextInputs, nor mount any new(max 100).
And it does not crash as expected.
Finally to make sure if it is actually remounting(a large number of TextInputs) that causes the issue. I tried to reproduce it in the app that I am working on, in which the crash was reported.
In the app there are 2 screens, one having 2 TextInputs and the other with 4, I kept navigating back and forth the screens, which of course remounts the entire screen contents, and eventually after a while I was able to get the crash.
With this I could infer that not letting TextInput
unmount is not a viable solution. But still no idea what exactly causing this!
NOTE
underlineColorAndroid
property, because I have tried overriding it with <item name="android:editTextBackground">@android:color/transparent</item>
, and no difference.ScrollView
.TextInput
was also not necessary to get crash, simply remounting those 100
TextInputs resulted in crash.Thanks!
@rimzici Yes that's true. The crash is related to remounting/instantiating a edittext sometimes the background drawables are null. But strangely enough, when you set <item name="android:editTextBackground">@android:color/transparent</item>
that wont happen. It seems that the drawables somehow got recycled after cloning and when set a background it can have a default value?
Thanks @rimzici.
It's disappointing to hear that simply setting <item name="android:editTextBackground">@android:color/transparent</item>
didn't fix it for you. At least you have a way of easily reproducing the error now and can try a few other things.
Please post any further observations that you may have.
Thanks @sunnylqm and @glenn-axsy! You are right, setting <item name="android:editTextBackground">@android:color/transparent</item>
does fix indeed.
I forgot that I had a splash theme set on my Main Activity, to cover the white screen while JS load.
Now I can confirm that the work around is effective in preventing crash.
Will update with any more information.
react-native 0.61.5 <-- is here too!
react-native 0.62.0.rc-1 <-- is here too!
Same error on [email protected]
Hitting many occurrences of same error caught by Sentry: https://sentry.io/share/issue/ac1e7c55f1594b118f0faaf8d11de5c4/
On RN 0.59.9
Same error on RN 0.55.4
Same issue on RN 2.0.1
don't set 'underlineColorAndroid' props to any TextInput and remove all text input background by native styles.
goto android\app\src\main\res\values\styles.xml
change that like below :
Same on RN 0.61.5
I found manual testing to be to be very hit and miss, so I wrote a component to automatically test some of the scenarios that people have been reporting above. You will find the component below. You just have to render it somewhere for it to do its job.
Doing this I found that you only need to add the following to the AppTheme in styles.xml as suggested by @Hopding
<item name="android:editTextBackground">@android:color/transparent</item>
Nothing else was required, and there was _no need_ to avoid setting
underlineColorAndroid
, so it didn't matter that React Native now sets it by default.The main downside of this fix is that you have to re-style your TextInputs to allow for the resulting loss of padding, and you also lose the actual underlining behaviour as well, which for us was a benefit as we always set it "transparent" to be consistent with iOS. If you need it you could make a wrapper component that watches
onFocus
andonBlur
and make your own underline.My version of React Native is 0.57.3
Here are some other things that I found using my test component:
- I couldn't cause the crash at all on my low-spec android tablet device. It was quite easy to reproduce however on my Samsung S6 Edge phone running Android 7. My guess is that there is a race condition that needs a faster device to provoke it.
- Scrolling the text inputs made no difference, and I could easily reproduce the problem without even using a ScrollView.
- Entering text wasn't necessary. Simply changing the focus was enough to cause the crash.
- It made no difference what color you set the underline to, even
undefined
caused the crash, but you would perhaps expect that since RN now defaults it to "transparent"- Having a fair number of TextInputs showing at once made a difference with the crash happening quicker with 100, than just 10 on the screen.
- I couldn't reproduce the crash with
displayForMs: 0
suggesting that it only occurs when the TextInputs have only recently been created.If you don't want to hang around while testing you can capture the output of
adb logcat
and look for the console messages produced by the component and the crash report.Here is my test component should you wish to use it. The test parameters are set to cause a crash typically in under 30 seconds for me.
/** * A test component to reproduce the crash reported at * https://github.com/facebook/react-native/issues/17530 */ import * as React from "react"; import { View, ScrollView, TextInput, Text, StyleSheet } from "react-native"; // These are the test parameters const params = { underlineColors: ["red", undefined, "transparent", "rgba(0, 0, 0, 0)"], // The colors to test numberOfInputs: 100, // How many TextInput to render at a time focusIntervalMs: 200, // How often to change focus between them displayForMs: 3000, // How long to display them (set to 0 for indefinite) delayDisplayForMs: 10, // How long to delay between displays withScrollView: false // Whether to use a ScrollView }; const testText = index => `Testing underlineColor = ${params.underlineColors[index] || "undefined"}`; class AndroidTextInputTest extends React.Component{ state = { underlineColorIndex: 0, showInputs: true, startKey: 0 }; mounted = false; focusInterval = undefined; textInputRefs = undefined; focussedInputIndex = 0; componentDidMount() { console.log(`Testing with params = `, JSON.stringify(params)); this.mounted = true; setTimeout(this._showInputs, params.delayDisplayForMs); setInterval(this._focusAnInput, params.focusIntervalMs); } componentWillUnmount() { clearInterval(this.focusInterval); this.mounted = false; } _focusAnInput = () => { if (this.mounted && this.textInputRefs) { if (this.focussedInputIndex >= this.textInputRefs.length) { this.focussedInputIndex = 0; } const textInputRef = this.textInputRefs[this.focussedInputIndex]; const textInput = this.refs[textInputRef]; if (textInput) { this.focussedInputIndex++; this.refs[textInputRef].focus(); } } }; _showInputs = () => { if (this.mounted) { console.log(testText(this.state.underlineColorIndex)); this.setState({ showInputs: true }); if (params.displayForMs) { setTimeout(this._unshowInputs, params.displayForMs); } } }; _unshowInputs = () => { this.focussedInputIndex = 0; this.textInputRefs = undefined; if (this.mounted) { let next = this.state.underlineColorIndex + 1; if (next === params.underlineColors.length) { next = 0; } this.setState({ underlineColorIndex: next, showInputs: false, startKey: this.state.startKey + params.numberOfInputs }); setTimeout(this._showInputs, params.delayDisplayForMs); } }; render() { const textInputs = []; const { underlineColorIndex } = this.state; const underlineColor = params.underlineColors[underlineColorIndex]; const refs = []; if (this.state.showInputs) { for (let i = 0; i < params.numberOfInputs; i++) { const key = this.state.startKey + i + ""; refs.push(key); textInputs.push( <TextInput ref={key} key={key} placeholder={key} underlineColorAndroid={underlineColor} style={styles.textInput} /> ); } if (!this.textInputRefs) { this.textInputRefs = refs; } } return ( <View style={styles.mainView}> <Text>{testText(underlineColorIndex)}</Text> {params.withScrollView ? ( <React.Fragment> <Text>With ScrollView</Text> <ScrollView>{textInputs}</ScrollView> </React.Fragment> ) : ( <React.Fragment>{textInputs}</React.Fragment> )} </View> ); } } const styles = StyleSheet.create({ mainView: { flex: 1, alignItems: "center" }, textInput: { backgroundColor: "white", margin: 5, width: 300 } }); export default AndroidTextInputTest;
Can confirm this fixed it for me !
I'm glad my test component and suggested solution worked for you @gagangoku
For those who want to see it in context the link is here
Perhaps you would be kind enough to add that link to your comment.
The fix from @glenn-axsy worked for me (as did the testing component 👏👏👏), but I ran into some trouble along the way which may help another lost soul:
My AppTheme was being improperly overridden in the AndroidManifest.xml
file, because of a mistake a developer had made when adding a splash-screen activity. Once I fixed and confirmed that the AppTheme was actually being used (eg. by changing the default text color and seeing it in the app), then the fix actually worked.
Thanks so much, and good luck out there!
It happens to me using expo. I run this command.
sudo expo start -c
and the issue is gone.
@HakimAsa I suggest using the testing component to make sure it has really gone.
Their weird thing is that the code has been working for a month without that issue. But after some repetitive reloading on changes, I ran into issue yesterday... Anyway I will try your suggestion @glenn-axsy
In my case it was happing within a FlatList when renderItem
returns <TextInput />
. So I solved that issue by returning <><TextInput /></>
@MahmoudHemaid the issue is so hard to reproduce that you may not have actually solved it. More information here.
android.graphics.drawable.Drawable$constantstate,newdrawable on a null reference error getting while i am clicking an image,placed on the right most corner. And that image was act like a toggle button. I am using RN 0.61.2. Some one please help me to solve the issue. its happens only in standalone apk
@glenn-axsy https://github.com/facebook/react-native/issues/17530#issuecomment-504044357
Doing this I found that you only need to add the following to the AppTheme in styles.xml as suggested by @Hopding
<item name="android:editTextBackground">@android:color/transparent</item>
https://github.com/facebook/react-native/pull/27782#issuecomment-575753501
The simplest example would be to just create an
EditText
with a nullAttributeSet
and no (0) default style attributes:
@Override
protected EditText createDummyEditText() {
return new EditText(getThemedContext(), null, 0);
}
ReactTextInput
may be overriden by sublasses that would like to provide their own instance of EditText
.
The EditText
android constructor:
public class EditText extends TextView {
public EditText(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
}
which calls the View
constructor (docs)
I'll keep investigating. Thanks
Hey @glenn-axsy , I've been struggling with this for hours so I really hope you can help me. I'm using your AndroidTextInputTest on my android phone. I'm running React Native with Typescript if that matters and doing so through Expo This means I don't have any EditText type stuff.
React native in package.json = "react-native": "^0.61.4"
I used the params:
const params = {
underlineColors: ["red", undefined, "transparent", "rgba(0, 0, 0, 0)"], // The colors to test
numberOfInputs: 100, // How many TextInput to render at a time
focusIntervalMs: 200, // How often to change focus between them
displayForMs: 3000, // How long to display them (set to 0 for indefinite)
delayDisplayForMs: 10, // How long to delay between displays
withScrollView: false, // Whether to use a ScrollView
};
And my output before getting the "Attempt to invoke virtual method" was:
Testing with params = {"underlineColors":["red",null,"transparent","rgba(0, 0, 0, 0)"],"numberOfInputs":100,"focusIntervalMs":200,"displayForMs":3000,"delayDisplayForMs":10,"withScrollView":false}
The params of calendarVisible is true and the state is true
Testing underlineColor = red
Testing underlineColor = undefined
Testing underlineColor = transparent
Testing underlineColor = rgba(0, 0, 0, 0)
Testing underlineColor = red
Testing underlineColor = undefined
Testing underlineColor = transparent
So my question from here is, how can I use these params and the output I saw before the crash to diagnose what is going wrong in my app?
Thank you for any help at all.
@ucheNkadiCode It's a test to quickly reproduce the issue, not a solution. The solution is
<item name="android:editTextBackground">@android:color/transparent</item>
@ucheNkadiCode It's a test to quickly reproduce the issue, not a solution. The solution is
<item name="android:editTextBackground">@android:color/transparent</item>
@sunnylqm I am sort of confused because I am using using react native, so I don't use item anywhere in my code.
I use a TextInput that looks like this:
TextInput
ref={key}
key={key}
placeholder={key}
underlineColorAndroid={underlineColor}
style={styles.textInput}
Thank you
@ucheNkadiCode
But for expo maybe you need to eject first to modify settings like this
@ucheNkadiCode
But for expo maybe you need to eject first to modify settings like this
Yea that would rightfully be the issue. I don't want to pay the price of ejecting my react native app this early into it's development. I'm hoping to find a solution that keeps me in React Native.
Thanks for your help
@axsy-dev @ucheNkadiCode
my comment was working in that direction, to fix this in a pull request to avoid the issues connected to TextInput
prop underlineColorAndroid
. ReactNative sets theme in a programmatic way... please review my comment and come back to me with some feedback as I could not solve this issue and I am working on other pull request now. Thanks
I was actually able to solve this issue by rewriting react native ReactTextInput
method
@Override
protected EditText createDummyEditText() {
return new EditText(getThemedContext(), null, 0);
}
But this is just disabling the style passed to the EditText component with getThemedContext()
additionally the stack tells us that this error is triggered by ReactEditText.onTouchEvent
, so when the user touch the TextInput
component.
my comment was working in that direction, to fix this in a pull request to avoid the issues connected to
TextInput
propunderlineColorAndroid
. ReactNative sets theme in a programmatic way... please review my comment and come back to me with some feedback as I could not solve this issue and I am working on other pull reqeusts now.I was actually able to solve this issue by rewriting react native
ReactTextInput
method@Override protected EditText createDummyEditText() { return new EditText(getThemedContext(), null, 0); }
But this is just disabling the style passed to the EditText component with
getThemedContext()
additionally the stack tells us that this error is triggered by
ReactEditText.onTouchEvent
, so when the user touch theTextInput
component.
@axsy-dev @fabriziobertoglio1987. So I don't have any elements I can find in my project directory with ReactEditText and I also don't have any .java files in my directory. I am using TypeScript with React native so the majority of my files are .tsx or .ts with the exception of plenty of node_modules.
I am not using Native Android unfortunately.
@ucheNkadiCode to solve this now you need to eject, otherwise recreate this scenario in reactnative, write a pull request, it gets merged in react-native then later expo.
@ucheNkadiCode I'm afraid I don't use Expo, but it sounds like @sunnylqm knows what he is talking about
I just faced same issue in expo.
I tried : watchman watch-del-all && expo r -c
but still now good news.
I am facing the same issue, which disappears if I change my TextInput into a text.
This comment from 2 years ago is still valid.
I've narrowed it down to a
<TextInput>
being rendered within in a FlatList. When I replace this with a<Text>
, the issue disappears.
Resetting the cache seems to help briefly, but my app would crash again after a few button clicks.
@diegoboston testing with my testing component you can reproduce this without FlatList. You can find the test component and a workaround/solution in my comment here.
I am using expo SDK 37 which uses react native 0.61 internally.
Its strange that I had no issue whatsoever, but all of a sudden when I restarted builder, this issue popped up. Is it not fixed yet ?
RN 0.62.2
+ Android
same here.
This error is invoked in production mode.
Clearing app cache from settings solved my issue, but that doesn't seem as an acceptable solution for this.
I worked on this issue and this are my findings (previous post is here).
1) We know that adding android:editTextBackground
with color/transparent
to the Theme fixes the issue
<item name="android:editTextBackground">@android:color/transparent</item>
2) Chaging the ReactEditTextShadowNode
method createDummyEditText
to the below code also fixes the issue (seems to me that disable all styleings for EditText)
@Override
protected EditText createDummyEditText() {
return new EditText(getThemedContext(), null, 0);
}
My understanding now of this issue is that in Android you can set styles in two ways
1) Writing XML like html elements and styles and apply them
2) Call the EditText
or View
constructor and pass the context and other attributes/styles with it.
ReactEditText
uses createDummyEditText
to create an EditText
instance and then change some styles (padding, layout ..etc), but this is something related to layout (padding, margins) and not background colors etc.. In fact I tried changing those lines of code to setBackgroundTint
to red
or transparent
and it did not work...
the background color is changed with the following method
On monday I'll try again to change the setBackgroundColor
method and set background color transparent at runtime ... That would be my first clue to solve this issue
The stack fails on createInternalEditText
/**
* May be overriden by subclasses that would like to provide their own instance of the internal
* {@code EditText} this class uses to determine the expected size of the view.
*/
protected EditText createInternalEditText() {
return new EditText(getThemedContext());
}
createInternalEditText
is the last method called before failure, the rest of the stack is from the Android sdk OpenSource library and it is not the real cause of the issue
Setting android:editTextBackground
is just probably over riding some item values from the Default Theme that is causing the issue. The issue is connected to the constructor passing getThemedContext
which includes also the theme
<item name="android:editTextBackground">@android:color/transparent</item>
For this reason I believe that the solution should be searched in how React handles context...
Guys restarting the packager and clearing cache worked for me!
But this is the temporary solution how can I fix this permanent?
I tried to set programmatically in java the background color to transparent, but still triggers the runtime error, which makes me believe the below code
<item name="android:editTextBackground">@android:color/transparent</item>
is just over-riding logic from
which is clearly the cause of the problem in the stack
That method is responsible for setting up the style of the EditText,
The problem is that the original issue stack seems to have different log and seems to be un-related to the attached test case. The below stack originated from ReactEditText.onTouchEvent
which means the user is touching the TextInput
and the error is triggered.
ORIGINAL LOG ERROR
java.lang.NullPointerException:
tempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference at
android.graphics.drawable.DrawableContainer$DrawableContainerState.getChild(DrawableContainer.java:888) at
android.graphics.drawable.DrawableContainer.selectDrawable(DrawableContainer.java:466) at
android.graphics.drawable.StateListDrawable.onStateChange(StateListDrawable.java:104) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.graphics.drawable.DrawableWrapper.onStateChange(DrawableWrapper.java:331) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.graphics.drawable.LayerDrawable.onStateChange(LayerDrawable.java:1488) at
android.graphics.drawable.Drawable.setState(Drawable.java:735) at
android.view.View.drawableStateChanged(View.java:18002) at
android.widget.TextView.drawableStateChanged(TextView.java:4097) at
android.view.View.refreshDrawableState(View.java:18071) at
android.view.View.setPressed(View.java:8543) at
android.view.View.setPressed(View.java:8521) at
android.view.View.onTouchEvent(View.java:11218) at
android.widget.TextView.onTouchEvent(TextView.java:8467) at
com.facebook.react.views.textinput.ReactEditText.onTouchEvent(ReactEditText.java:150)
Other type of errors https://github.com/facebook/react-native/issues/17530#issuecomment-376917781
OTHER LOG ERRORS
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:875)
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1158)
at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:433)
at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:258)
at android.view.View.computeOpaqueFlags(View.java:16791)
at android.view.View.setBackgroundDrawable(View.java:21710)
at android.view.View.setBackground(View.java:21603)
at android.view.View.
on the other side I ask myself if https://github.com/facebook/react-native/issues/17530#issuecomment-504044357 is an acceptable example, as it does not manually cause the error by clicking the TextInput but by doing it programmatically..
I am sure somebody in this discussion will make proper research and solve this issue. Thanks a lot and good luck! :smiley:
Guys, try running "npm install" again. It worked for me.
I've tried adding <item name="android:editTextBackground">@android:color/transparent</item>
and this stops the app from crashing however the text box just keeps flashing between large and small and is unusable, has anyone else had this?
In my case, I use styled-components, I set a props name is "right", I think it is special, I change to "isRight" solved my problem.
Take release build and test it on that apk you never seen this error
The original comment reports a problem obtained through the analytics bug report, and not an error in development, I think we need to stay focused.
You can try both and either of the points, whichever works for your app:
seems that there is a related issue open https://issuetracker.google.com/issues/37068452 on Android project
- Create a custom Drawable implementation that doesn't override getConstantState().
- Create a LayerDrawable instance, with an instance of the custom drawable as child.
- Call mutate() on the LayerDrawable.
Drawable dummyDrawable = new Drawable() {
@Override
public void draw(Canvas canvas) {
canvas.drawColor(Color.RED);
}
@Override public void setAlpha(int alpha) {}
@Override public void setColorFilter(ColorFilter cf) {}
@Override public int getOpacity() { return 0; }
};
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[] { dummyDrawable });
layerDrawable.mutate();
In our case the runtime error is triggered at this line from ReactEditText
(inherits from AppCompatEditText)
https://github.com/facebook/react-native/issues/17530#issuecomment-615131077
<TextInput style={styles.input} />
will send the information from JavaScript runtime to Android as JSON through the ReactNativeBridge, Android Java API will use the information to create a View
instance and inflate (display) it in the screen.
It will pass a Context
object to the View
constructor that will inflate the deault layout for that <TextInput />
, then anytime we change a prop like underlineColorAndroid
, we will call a specific Android API method for ex. setUnderlineColorAndroid("red")
and the Android API will take care of updating <TextInput />
underline color.
If 37068452 is causing the Runtime, then we must be mutating()
a BackgroundDrawable
maybe by changing the underlineColor
, but the error is triggered in the View
constructor when we pass the Context
.
I will try debugging the Android stack, but first I will try to transform the present example in a Minimum Reproducible Example and remove any properties that are not essential to reproduce the bug.
I was able to create a Minimum Reproducible Example.
The issue is caused from the TextInput key prop.
Re-rendering a high number of TextInput components with key prop will cause the runtime error.
The number of TextInput
s seems crucial to trigger the crash.
// Does not crash after testing for 5 minutes
for (let i = 0; i < 5; i++) { ..
// Crashes after 20 seconds
for (let i = 0; i < 100; i++) { ..
// Crashes after 1 second
for (let i = 0; i < 1000; i++) { ..
The crash does not reproduce if you remove the TextInput
key prop. I will investigate and try to fix it. Run this example to reproduce it.
import * as React from "react";
import { View, TextInput } from "react-native";
class App extends React.Component{
state = { startKey: 0 };
componentDidMount() {
this.interval = setInterval(this.updateKey, 3000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
updateKey = () => {
this.setState({
startKey: this.state.startKey + 100
});
};
render() {
const textInputs = [];
for (let i = 0; i < 100; i++) {
const key = (this.state.startKey + i).toString();
console.log("key", key);
// REMOVE KEY PROP TO FIX THIS
textInputs.push(
<TextInput key={key} />
);
}
return (
<View>
{ textInputs }
</View>
);
}
}
export default App;
The same issue can be reproduced with a FlatList, if your data
prop includes a key
, index
or id
like this [{ key: "1"}, {key: "2"}, .. {key: "5000"}]
, automatically the key
will be used for your List and causes the Runtime. Removing those keys from the data
array fixes the error and removes automatic caching.
import * as React from "react";
import { Text, FlatList, View, TextInput } from "react-native";
class App extends React.Component{
state = { startKey: 0 };
componentDidMount() {
this.interval = setInterval(this.updateKey, 3000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
updateKey = () => {
this.setState({
startKey: this.state.startKey + 100
});
};
render() {
const textInputs = [];
for (let i = 0; i < 5000; i++) {
const notKey = (this.state.startKey + i).toString();
console.log("key", notKey);
// REMOVE KEY OR ID FIELD TO FIX THIS
// replacing notKey with key will trigger the runtime
textInputs.push(
{ notKey }
);
}
return (
<FlatList
data={textInputs}
renderItem={({item}) => <TextInput value={"testing"} />}
/>
);
}
}
export default App;
The issue seems to be caused by this line of code. I commented the line and replaced it with const key = 500;
and the error would not re-reproduce..
An example is with keyExtractor(item, ii)
with item = {"key":"450"}
, ii = 50
and return value key = 450
will cause the crash, but I believe this is not the real cause, but just indication that key is causing the problem. I'll keep looking into this. I am looking for a job. Thanks a lot. I wish you a good weekend.
| WITH RUNTIME |
|:-------------------------:|
| |
| WITHOUT RUNTIME |
|:-------------------------:|
| |
@fabriziobertoglio1987 I have a similar conclusion https://github.com/facebook/react-native/issues/17530#issuecomment-573934341 ,that is , related to remounting/instantiating an edittext. At that time I did not understand why the textinput would recreate/reinstantiate when they seemed have no reason to. Now it sounds like keys might be the cause.
The error throws from here
where the array mDrawableFutures
is not null but some of its child elements could be null.
mDrawableFutures
can only be cloned from others
which means it was non-null when it was being cloned but somehow some of its child elements got destroyed after.
The following is my guess: The key props would trigger a diffing process, which would construct shadow nodes for textinputs. And during the process the drawable states would get cloned. However there might be a race condition/non thread-safe operation that destroyed some of the drawable states while they still might be in use. @fabriziobertoglio1987
thanks a lot @sunnylqm I believe in the power of collaboration and I'm trying to land this pull request to find some work.
I believe the issue is connected to some dirty parameters passed when using the key
and React.PureComponent.
You are right, in fact this problem is experienced only when using TextInput
component. For example replacing TextInput
with Text
in renderItem
will fix this issue
<FlatList
renderItem={({item}) => <TextInput value={"testing"} />}
The difference between using Text
and TextInput
is that const element
will be a ForwardRef
with TextInput
. In the case below TextInput
creates a runtime when reaches a certain key. I also removed underlineColorAndroid="transparent"
and it is not the cause of the error, but I left it in the logs below.
console.log("element", element);
//=> element <Text value="testing" />
//=> element <ForwardRef(TextInput) allowFontScaling={true} rejectResponderTermination={true} underlineColorAndroid="transparent" value="testing" />
TextInput returns a forwardRef
I believe a method in the Java API is called from the TextInput
javascript API, but with missing/dirty parameters. This may be causing the NPE Runtime Error, but I need to investigate every aspect of the JS TextInput API to understand the reason.
I think the key
prop is causing issues because the React
mechanism is based on comparing the key
prop, if no key prop mechanism is present, then not caching and subsequent no error.
Tomorrow I will try to set a breakpoint in your in the code you referenced in the above message
Thanks a lot for the help. Hopefully we will be able to write a Pull Request together and fix this issue. I wish you a good evening. Fabrizio
@sunnylqm
TOO LONG DON'T READ
I am writing a pull request to fix this issue. It is very easy to fix.
The issue is caused from the default BackgroundDrawable used in EditText initialization
The Drawable is the one from the theme we are using Theme.AppCompat.Light.NoActionBar
. Changing the Drawable can be done by changing the template xml files used to initialize the react-native android project with react-native init script.
I will use either one provided by default from android or I will create a custom drawable and include it in every project initialization.
<item name="android:editTextBackground">@android:drawable/edit_text</item>
or
<item name="android:editTextBackground">@drawable/custom_background_drawable</item>
LONG VERSION
I quote sunnylqm https://github.com/facebook/react-native/issues/17530#issuecomment-660506001
The following is my guess: The key props would trigger a diffing process, which would construct shadow nodes for textinputs. And during the process the drawable states would get cloned. However there might be a race condition/non thread-safe operation that destroyed some of the drawable states while they still might be in use.
This line android:editTextBackground
fixes the error, but WHAT does this line do in ReactNative?
1) The AndroidManifest.xml
assignes the android:theme="@style/AppTheme"
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.awesomeproject">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".MainApplication"
android:theme="@style/AppTheme">
2) We change the AppTheme
in res/values/styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:textColor">#000000</item>
<item name="android:editTextBackground">@android:drawable/edit_text</item>
</style>
</resources>
3) EditText
constructor will call super(context)
. The context
object includes the layout
and theme
(AppTheme
).
The View
constructor will obtain the style/theme/layout information from the context
object and create an instance of EditText
with those styles (xml is like html), inflate it and display it on the screen.
Android uses xml like html to render static views, while Java is used to render dynamic content (like JavaScript in Web).
4) ReactNative
builds on top of the Context
API, but will use the same pattern from 1-3.
Initialize the views with the context
object, then use JavaScript to make dynamic changes without changing the context
instance directly, but using the react-native
bridge via the Android API.
| BEFORE | AFTER | AFTER with TextInput style props |
|:-------------------------:|:-------------------------:|:-------------------------:|
| | | |
I am preparing a Pull Request to change the default Drawable used for EditText at initialization.
The Drawable from Theme Theme.AppCompat.Light.NoActionBar is causing this issue, replacing it with another drawable should fix it. The drawable @android:drawable/edit_text
is too heigh for our design. The Parent View adapts to the default drawable height if height is heigher the parent. I believe ReactNative is using a default drawable with low height and then adapting it with match_parent
to the parent View.
1) OPTION 1 - Find a drawable from another theme
2) OPTION 2
Create a new drawable in the react-native template based on the one availabe in the android project with low height to allways match_parent View.
I added to my android project the following drawable with height few pixels
The background drawable adapts to his parent View height of 10
The background drawable adapts to his parent View height of 100
seems to work with small background drawables, then we just need the react-native init
script to initialize projects using this background drawable by default. I will add the above explaiend changes to the files below in a pull request.
Thanks a lot. Fabrizio
Facing the same issue with RN 0.61.0 + Android API level 28.
I have narrowed it down to some combination of Flatlist, TextInput and nested Component renders
@fabriziobertoglio1987 i have tried this way but maybe i missed sth that i didnot make it work. I know little about android and i am glad you can fix it. While i am still interested in the key props issue.
@fabriziobertoglio1987 Is there anyway in react native js code which I can add so as to fix this issue quickly? Let me know.
@asmi24886 you can find a testing component to reliably reproduce this issue and a native code/configuration workaround in my comment here
I don't think there is a workaround using JS code only.
This is the continuation of my previous message https://github.com/facebook/react-native/issues/17530#issuecomment-660908150, my efforts to find a freelance job and write the pull request to close this issue.
I created a custom drawable based on Theme.AppCompat.Light
.
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="@dimen/abc_edit_text_inset_horizontal_material"
android:insetRight="@dimen/abc_edit_text_inset_horizontal_material"
android:insetTop="@dimen/abc_edit_text_inset_top_material"
android:insetBottom="@dimen/abc_edit_text_inset_bottom_material">
<selector>
<item android:state_enabled="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
<item android:state_pressed="false" android:state_focused="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
<item android:drawable="@drawable/abc_textfield_activated_mtrl_alpha"/>
</selector>
</inset>
The Runtime is caused from the following entry, if I remove this line an exact copy of the current Drawable from react-native
works and does not trigger the Runtime Error. I included the Minimal Reproducible Example in my https://github.com/facebook/react-native/issues/17530#issuecomment-660017858
<item android:state_pressed="false" android:state_focused="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
I'm writing a Pull Request, once the pull request is merged you will be able to upgrade with the upgrade-helper.
The Pull Request will include a reproduction of this scenarios in RNTester application, changes to the template and addition of the above custom drawable to avoid this issue.
This is a video showcasing the runtime error when the Drawable has line <item android:state_pressed="false" android:state_focused="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
This is a video showcasing the fix (no runtime error) when the Drawable does not have line <item android:state_pressed="false" android:state_focused="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
As displayed in the below screenshot, I am just removing the following line from the drawable xml file
xml
<item android:state_pressed="false" android:state_focused="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
I am not changing the style. The Drawable is the same used from AppCompat and the style will be the same, but it will not trigger the runtime error
I'll try to publish the pull request tomorrow.
Thanks a lot sunnylqm for collaborating with me to write https://github.com/facebook/react-native/pull/29452 which solves this issue.
There seems to be a bug in Drawable.mutate() in some devices/android os versions even after you check the constant state. This error is hard to reproduce and to fix, so just try to catch the exception to prevent crash.
The issue is caused by this line in extras/android/support/v7/appcompat/res/drawable/abc_edit_text_material.xml.
<item android:state_pressed="false" android:state_focused="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
The above line creates a StateListDrawable which will change the TextInput
background Image (Background Drawable) depending on the state of the TextInput
.
state_pressed="false"
and state_focused="false"
will trigger a change of the TextInput BackgroundDrawable. The images are not the cause of the issue, but I included them for documentation purposes.
| abc_textfield_activated_mtrl_alpha | abc_textfield_default_mtrl_alpha |
|:-------------------------:|:-------------------------:|
| | |
Inside DrawableContainer.getChild() ConstantState variable cs is null
. Calling null.newDrawable(mSourceRes)
triggers a Null Pointer Exception. This call is the result of the change of state of the TextInput, in this stack trace after pressing it.
mDrawableFutures
does not include the correct list of entries https://github.com/facebook/react-native/pull/29452#issuecomment-662616018.
final ConstantState cs = mDrawableFutures.valueAt(keyIndex);
final Drawable prepared = prepareDrawable(cs.newDrawable(mSourceRes));
More info in the previous comments https://github.com/facebook/react-native/issues/17530#issuecomment-661174770 https://github.com/facebook/react-native/issues/17530#issuecomment-660908150 https://github.com/facebook/react-native/issues/17530#issuecomment-660506001 https://github.com/facebook/react-native/issues/17530#issuecomment-660458191 https://github.com/facebook/react-native/issues/17530#issuecomment-660017858 https://github.com/facebook/react-native/issues/17530#issuecomment-659422298 https://github.com/facebook/react-native/issues/17530#issuecomment-645851033 https://github.com/facebook/react-native/issues/17530#issuecomment-632795323
Thanks a lot
I wish you a good day
Fabrizio
@fabriziobertoglio1987 Is the above comment a work around or an actually implementable fix that needs to be added to react native, we are currently on RN 0.59.3 and are getting this error only in production use. We cannot seem to replicate in development.
@Coffeegerm The above comment https://github.com/facebook/react-native/issues/17530#issuecomment-662000718 is a brief explanation of how my pull request https://github.com/facebook/react-native/pull/29452 fixes this issue. Once the pull request is merged in react-native
1) New apps will not have this error
2) Existing Apps will upgrade and they will not experience the error. Read More about upgrading at upgrading#3-upgrade-your-project-files to learn more about how to apply the changes in your /android
folder when you upgrade your application.
If you do not want to upgrade, you can check my PR https://github.com/facebook/react-native/pull/29452 and add those changes to your project android
folder. You don't need to make changes to react-native
sourcecode, as the configuration changes from this PR are not in the /ReactAndroid
Java codebase, but in the Android
template used to initialize the project.
I am currently working on other issues, but I will come back, reply to any feedback and make any necessary improvements to my Pull Request.
Please come back to me with any suggestion for improvement and feedback.
I wish you a good weekend
Thanks a lot for your help
Fabrizio
Just saw a commit that sounds related https://github.com/facebook/react-native/commit/1e4d8d902daca8e524ba67fc3c1f4b77698c4d08
we were generating strictly too many Create+Delete operations that were redundant and could cause consistency issues, crashes, or bugs on platforms that do not handle that gracefully -
especially since the ordering of the Create+Delete is not guaranteed (a reparented view could be created "first" and then the differ could later issue a "delete" for the same view).
@fabriziobertoglio1987
Any idea of how someone could fix this issue while using Expo, therefore without access to the project's android folder? 😅
@divonelnc There is a workaround: Use a new key everytime a textinput is rendered, for example,
<TextInput key={Math.random()} />
And of course it may cause some other problems and performance loss.
@sunnylqm Unfortunately that didn't help 😞. I am still having it crash randomly on the screen with dozens of text inputs.
I can confirm this issue in Production! RN: 0.62.2 😕
The same issue occurred in RN 0.63.2 :(
This commit may be fix this issue:
https://github.com/facebook/react-native/commit/a5b5d1a805a9c54d325763b432be1cf2c8811dc9
Same issue with Expo and RN sdk https://github.com/expo/react-native/archive/sdk-38.0.2.tar.gz
Wow this was frustrating. @WilliamAlexander @Hopding solution works. I know because I could repro it every time before.
// styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:editTextStyle">@style/AppEditTextStyle</item>
<item name="editTextStyle">@style/AppEditTextStyle</item> <!-- For compatibility with the support library -->
<item name="android:editTextBackground">@android:color/transparent</item>
</style>
<style name="AppEditTextStyle" parent="@style/Widget.AppCompat.EditText">
<item name="android:background">@android:color/transparent</item>
</style>
</resources>
Here's a pretty good workaround. Make a wrapper for whatever text input component you're using, and generate a key for it with useMemo. This way a single text input will always have the same key through re-renders, and you don't have to write keys for all your text inputs either.
export default (props: TextInputProps) => {
const key = useMemo(() => {
return Math.random().toString()
}, [])
return (
<TextInput key={key} {...props} />
)
}
If your are using expo
I got this error after upgrading from expo SDK 38 to 39.
I had to clean both my expo cache (expo -r c) + the expo mobile app cache (i uninstall and re-install it to be sure) and the error was gone.
@dpnick the bug is very hard to reproduce. I suggest using the testing component I posted here to make sure it really has gone.
Getting this error in production and I'm not able to reproduce this issue, my RN version is 0.62.2, here are my logs from firebase crashlytics:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)' on a null object reference
at android.graphics.drawable.DrawableContainer$DrawableContainerState.createAllFutures(DrawableContainer.java:880)
at android.graphics.drawable.DrawableContainer$DrawableContainerState.getOpacity(DrawableContainer.java:1163)
at android.graphics.drawable.DrawableContainer.getOpacity(DrawableContainer.java:434)
at android.graphics.drawable.InsetDrawable.getOpacity(InsetDrawable.java:259)
at android.view.View.computeOpaqueFlags(View.java:19424)
at android.view.View.setBackgroundDrawable(View.java:24701)
at android.view.View.setBackground(View.java:24594)
at android.view.View.<init>(View.java:6191)
at android.widget.TextView.<init>(TextView.java:1223)
at android.widget.EditText.<init>(EditText.java:106)
at android.widget.EditText.<init>(EditText.java:102)
at android.widget.EditText.<init>(EditText.java:98)
at android.widget.EditText.<init>(EditText.java:94)
at com.facebook.react.views.textinput.ReactTextInputShadowNode.createInternalEditText(ReactTextInputShadowNode.java:258)
at com.facebook.react.views.textinput.ReactTextInputShadowNode.setThemedContext(ReactTextInputShadowNode.java:78)
at com.facebook.react.uimanager.UIImplementation.createView(UIImplementation.java:243)
at com.facebook.react.uimanager.UIManagerModule.createView(UIManagerModule.java:469)
at java.lang.reflect.Method.invoke(Method.java)
at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372)
at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:151)
at com.facebook.react.bridge.queue.NativeRunnable.run(NativeRunnable.java)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:27)
at android.os.Looper.loop(Looper.java:237)
at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:226)
at java.lang.Thread.run(Thread.java:919)
@AbdelkhalekESI the bug is very hard to reproduce. Have you tried the testing component I posted here?
I wrote a pull request that fixes this issue https://github.com/facebook/react-native/issues/17530#issuecomment-663577143
Please head over to the pr https://github.com/facebook/react-native/pull/29452 follow the instructions https://github.com/facebook/react-native/wiki/Building-from-source#publish-your-own-version-of-react-native and let me know if you need any help. I'll try to check this weekend if a separate pr needs to be written for Expo, but I believe they will just get the fix by upgrading reactnative once this pr is merged and released. Thanks a lot. I wish you a good night
more info in my previous posts https://github.com/facebook/react-native/issues/17530#issuecomment-662000718
Same issue in version "react-native": "0.63.3"
just clear your cache of Expo in mobile application (if you use mobile application) or cache of Expo application in any platform you use.
@tzeneng96 ok, clearing the cache works with the app, but it is not an acceptable solution, because the problem reoccurs!
@AbdelkhalekESI the bug is very hard to reproduce. Have you tried the testing component I posted here?
I was able to reproduce this bug using this component. I have also received many logs of this crash in production. The project currently has react at version 0.63.3.
I don't know if I got it wrong, but In this topic quoted by @glenn-axsy, from what I understand they managed to solve by adding in andoid\app\src\main\res\values\styles.xml the item:
"item name="android:editTextBackground">@android:color/transparent /item"
I am still testing the solution.
@thiagocristianno your understanding is correct, though it's not a perfect solution and I believe it doesn't help Expo developers as they can't control that setting.
Wow this was frustrating. @WilliamAlexander @Hopding solution works. I know because I could repro it every time before.
// styles.xml<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="android:editTextStyle">@style/AppEditTextStyle</item> <item name="editTextStyle">@style/AppEditTextStyle</item> <!-- For compatibility with the support library --> <item name="android:editTextBackground">@android:color/transparent</item> </style> <style name="AppEditTextStyle" parent="@style/Widget.AppCompat.EditText"> <item name="android:background">@android:color/transparent</item> </style> </resources>
@@jordangrant , where did you see the workaround?
Wow this was frustrating. @WilliamAlexander @Hopding solution works. I know because I could repro it every time before.
// styles.xml<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="android:editTextStyle">@style/AppEditTextStyle</item> <item name="editTextStyle">@style/AppEditTextStyle</item> <!-- For compatibility with the support library --> <item name="android:editTextBackground">@android:color/transparent</item> </style> <style name="AppEditTextStyle" parent="@style/Widget.AppCompat.EditText"> <item name="android:background">@android:color/transparent</item> </style> </resources>
@@jordangrant , where did you see the workaround?
@bobowinca This is an extremely long thread and that solution 100% worked for me. RN 63.3 no Expo
@jordangrant , Doh! Always look before ask. I have failed. Thanks you Sir.
Also sounds like you were able to reproduce the issue consistently. I am wondering how you do that. I have only seen stack trace so far. I am figuring out ways to verify the fix.
@bobowinca the testing component I posted here should help you reproduce it consistently.
@bobowinca the testing component I posted here should help you reproduce it consistently.
works like a charm! Thanks Glenn!
Adding <item name="android:editTextBackground">@android:color/transparent</item>
to styles.xml is working!
Method with adding to TextInput's key={Math.random().string()}
was working but rerenders causes keyboard hide every time after second - it was unacceptable.
Most helpful comment
This issue has been causing our app to crash in production as well. It's a nasty bug, because it is really difficult to reproduce. We've found a promising fix for our app, and I'd like to share our findings here to hopefully save others some time & frustration.
Specs and Versions
This bug has caused our app to crash on Samsung, Google, and LG Android devices. We've had crash reports from the following Android versions:
8.0.0
8.1.0
7.1.1
Our app is running:
react-native
: 0.53.0react
: 16.2.0What causes the crash
Like others have noted in this thread, the issue seems to be triggered by rendering some combination of
TextInput
,FlatList
, andScrollView
components. In our case, we have a screen containing a singleTextInput
rendered above aFlatList
. When one of the items in theFlatList
is tapped, the app navigates to a new screen containing a form. This form's root component is aScrollView
that contains a number ofTextInput
components (along with some buttons and other custom components). Our app crashes when the user taps one of theseFlatList
items (note that it doesn't happen _every_ time).Reproducing this issue is difficult. In fact, we've been unable to do so. But we know that the crash occurs at this point in the workflow by watching our Appsee session recordings.
Because we can't reproduce the issue, we've had to rely on the crash logs from Appsee to debug it. I've copied the stack trace from the crash reports below (and omitted some noisy sections). It's more or less identical to the stack traces posted in this thread by others:
Source of the problem
After reading through this thread and doing a few hours or research, I found the
underlineColorAndroid
prop handler in theReactTextInputManager.java
file:The bug report linked to in the comment contains the following stack trace:
This matches the stack trace we we are encountering in our app. I don't pretend to fully understand the underlying problem, but it seems likely that the cause of our app crashing in production is due to the
Drawable.mutate()
bug being triggered. This happens when we try to set theunderlineColorAndroid
prop on ourTextInput
component (and thus invoke theReactTextInputManager.setUnderlineColor
method).Our app was rendering a
TextInput
with the following props, one of which wasunderlineColorAndroid="transparent"
:How we fixed it
We needed to set this prop in order to remove the underline from the
TextInput
components in our app. But based on our findings, its prop handler appeared to be triggering an Android bug that caused the app to crash occasionally.Fortunately, there is another way to remove underlines from
TextInput
components on Android. You can add a line to theandroid/app/src/main/res/values/styles.xml
file:Note that I've also seen the following suggested, but this did not remove the underlines for us:
This does not address the underlying issue. It is just a workaround that involves avoiding usage of the
underlineColorAndroid
prop onTextInput
components.I cannot yet say with certainty that this actually works, because I've been unable to reproduce the issue locally. We'll be deploying this change in an update to our app in the coming weeks. After that, we'll have to wait awhile to see if it occurs anymore. I'll try to report back with our findings.
Good luck to everybody wrestling with this frustrating issue! I hope this helps.