Reputation: 105
I have a TextView
and I want to get some specific line's text of it but when I use txt.getLayout.getLineStart(1)
it returns null and crashes the app, what is the reason?
TextView txt = (TextView)mRootView.findViewById(R.id.txt);
int start = txt.getLayout().getLineStart(1);
int end = txt.getLayout().getLineEnd(1);
String first = txt.getText().subSequence(start,end).toString();
Crash log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sattva.animalsencyclopedia, PID: 11244
java.lang.NullPointerException
at com.sattva.animalsencyclopedia.fragments.FragmentInformation.onViewCreated(FragmentInformation.java:110)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1086)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
Upvotes: 0
Views: 838
Reputation: 1689
Probably you didn't find this view using findViewById()
method in correct way. You are using fragment and probable you have something like getActivity().findViewById()
. Try in your onCreateView()
method do something like this view.findViewById()
, where view
is the result of inflating.
As @pskink mentioned from the docs: returns Layout the Layout that is currently being used to display the text. This can be null if the text or width has recently changes.
Try to call this code in onStart or onCreate method, but you should make a txt
as a class member variable.
int start = txt.getLayout().getLineStart(1);
int end = txt.getLayout().getLineEnd(1);
String first = txt.getText().subSequence(start,end).toString();
Upvotes: 1