Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempt to invoke virtual method 'int android.text.Layout.getLineCount()' on a null object reference

I am getting null pointer exception randomly, usually it works and sometime it crashes, I had searched a lot but didn't get any help as it there is no proper line from where I get any help,

I am also using handler with it.

My logcat error is as follows and code is added below it,

 java.lang.NullPointerException: Attempt to invoke virtual method 'int android.text.Layout.getLineCount()' on a null object reference
 at android.widget.TextView.onMeasure(TextView.java:6703)
 at android.view.View.measure(View.java:17547)
 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
 at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
 at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
 at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
 at android.view.View.measure(View.java:17547)
 at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:727)
 at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:463)
 at android.view.View.measure(View.java:17547)
 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
 at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
 at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
 at android.view.View.measure(View.java:17547)
 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
 at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
 at android.view.View.measure(View.java:17547)
 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
 at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
 at android.view.View.measure(View.java:17547)
 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
 at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
 at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
 at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
 at android.view.View.measure(View.java:17547)
 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
 at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
 at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2615)
 at android.view.View.measure(View.java:17547)
 at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2015)
 at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1173)
 at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1379)
 at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
 at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
 at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
 at android.view.Choreographer.doCallbacks(Choreographer.java:580)
 at android.view.Choreographer.doFrame(Choreographer.java:550)
 at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
 at android.os.Handler.handleCallback(Handler.java:739)
 at android.os.Handler.dispatchMessage(Handler.java:95)
 at android.os.Looper.loop(Looper.java:135)
 at android.app.ActivityThread.main(ActivityThread.java:5254)
 at java.lang.reflect.Method.invoke(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:372)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

This is my code as follows, here it usually crash on click of register or forget button on first install and after that it usually works fine but sometime it gives me error,

 public class Login extends AppCompatActivity implements View.OnClickListener,ProcessedResult
 {
    private Handler uiThreadHandler;
    private Context context;
    private EditText ed_password,ed_Username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_login);

      StorageManager storageManager=new StorageManager(this,"abc");
                    String accessTokenCheck=storageManager.getValue(Constants.SharedPreferences.LACCESSTOKEN, null);
      if(accessTokenCheck!=null)
                        GeneralFunctions.moveToNextActivity(MainActivity.class,this);

      uiThreadHandler = new UIThreadHandler();
      new Thread(new Runnable() {
         @Override
         public void run() {
             init();
         }
        }).start();
       }

       //Initialization part
       private final void init()
       {
          context=this;

          FontsManager.initFormAssets(this, "fonts/Lato-Regular.ttf");
          FontsManager.changeFonts(this);

          TextView myTextView =  GeneralFunctions.findViewByIdAndCast(this, R.id.login_tv_noAccount);
          myTextView.setMovementMethod(new LinkTouchMovementMethod());
                    myTextView.setHighlightColor(getResources().getColor(android.R.color.transparent));
          SpannableString mySpannable = new SpannableString(myTextView.getText().toString());

          TouchableSpan touchableSpan = new TouchableSpan(Color.parseColor("#606060"),getResources().getColor(R.color.colorBlue),Color.TRANSPARENT) {
          @Override
          public void onClick(View textView) {
                            GeneralFunctions.simpleMoveToNextActivity(Register.class, context);
                        }
                    };

          mySpannable.setSpan(touchableSpan, GeneralFunctions.getText(myTextView).indexOf("Register"), GeneralFunctions.getText(myTextView).length(), 0);
          myTextView.setText(mySpannable, TextView.BufferType.SPANNABLE);

          TextView tv_forgetPassword =  GeneralFunctions.findViewByIdAndCast(this,R.id.login_tv_foregetPassword);
                    GeneralFunctions.setTextColorSelector(Color.parseColor("#606060"),getResources().getColor(R.color.colorBlue),tv_forgetPassword);
                    tv_forgetPassword.setOnClickListener(this);

          ed_password = (EditText) findViewById(R.id.login_ed_password);
          ed_Username = (EditText) findViewById(R.id.login_ed_usrName);
          ed_password.setTransformationMethod(new AsteriskPasswordTransformationMethod());

          Button bt_Login= GeneralFunctions.findViewByIdAndCast(this,R.id.login_bt_signin);
                    setSelector(R.drawable.big_green_btn_normal, bt_Login);

          Button bt_linkedInd= GeneralFunctions.findViewByIdAndCast(this,R.id.login_bt_linkedin);
                    setSelector(R.drawable.big_blue_btn_normal, bt_linkedInd);
          }

          private final void setSelector(final int resourceId,final Button button)
          {
              button.setOnClickListener(this);
              try
              {
                String name = getNameofResyrce(activity,resourceId);
                String newString=name.replace("normal","pressed");

                StateListDrawable states = new StateListDrawable();
                states.addState(new int[] {android.R.attr.state_pressed}, getDrawablebyName(activity,newString));
                states.addState(new int[] {android.R.attr.state_focused},getDrawablebyName(activity, newString));
                states.addState(new int[]{}, getDrawablebyName(activity, name));
                if(view instanceof Button)
                   ((Button)view).setBackground(states);
                else
                   if(view instanceof ImageView)
                       ((ImageView)view).setImageDrawable(states);
               } catch (Exception e)
               {
               }
          }


                public static synchronized Drawable getDrawablebyName(Context context,String name)
                {
                    Resources resources = context.getResources();
                    final int resourceId = resources.getIdentifier(name, "drawable", context.getPackageName());
                    return resources.getDrawable(resourceId);
                }

                @Override
                public void onClick(View v) {
                    switch (v.getId())
                    {
                        case R.id.login_bt_linkedin:
                        {
                            DWebView transparentDialog = DWebView.newInstance();
                            showProgressDialog(transparentDialog, Constants.DialogConstants.WEB);
                        }
                        break;
                        case R.id.login_bt_signin:
                            uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.VALIDATION);
                            break;
                        case R.id.login_tv_foregetPassword:
                            GeneralFunctions.simpleMoveToNextActivity_Without_history(ForgetPassword.class, context);
                            break;
                    }
                }

        //Listener part
                @Override
                public <IResponse, IMethod> void processedResult(IResponse iResponse, IMethod iMethod) {
                    switch (iMethod.toString())
                    {
                        case "back":
                            finish();
                            break;
                        case "showProgress":
                         uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.SHOWDIALOG);
                            break;
                        case "hideProgress":
                            uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.HIDEDIALOG);
                            break;
                    }
                }


        //Handler part
                private class UIThreadHandler extends Handler {
                    @Override
                    public void handleMessage(Message msg)
                    {
                        switch (msg.what) {
                            case Constants.ActivityBasicsCode.SETERROR:
                            {
                                CustomException exception=(CustomException)msg.obj;
                                TextView editText=exception.getTextView();
                                editText.setError(exception.getMessage());
                                editText.setFocusable(true);
                                editText.requestFocus();
                            }
                            break;
                            case Constants.ActivityBasicsCode.HIDEDIALOG:
                                hideProgressDialog(Constants.DialogConstants.Transparent);
                                break;
                            case Constants.ActivityBasicsCode.SHOWDIALOG: {
                                DTDialog dtDialog=DTDialog.newInstance();
                                showProgressDialog(dtDialog,Constants.DialogConstants.Transparent);
                            }
                            break;
                            case Constants.ActivityBasicsCode.VALIDATION: {
    //Here validation is done in separate thread
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try
                                        {
                                            if (Validation.validate(Login.this))
                                                GeneralFunctions.moveToNextActivity(MainActivity.class, context);
                                        } catch (CustomException e)
                                            {
    //Catch exception for validation is thrown here
                                                Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.SETERROR);
                                                message.obj=e;
                                                uiThreadHandler.sendMessage(message);
                                            }finally {
                                                uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.HIDEDIALOG);
                                            }
                                        }
                                    }).start();
                                    break;
                                }
                            }
                            super.handleMessage(msg);
                        }
                    }

                public final<T extends DialogFragment> void showProgressDialog(T currentDialog,String tagName)
                {
                    FragmentManager fragmentManager =getSupportFragmentManager();
                    currentDialog.show(fragmentManager, tagName);
                }

                public final void hideProgressDialog(String tagName)
                {
                    FragmentManager fragmentManager =getSupportFragmentManager();
                    DialogFragment transparentDialog = (DialogFragment)fragmentManager.findFragmentByTag(tagName);
                    if (transparentDialog == null) {
                        return;
                    }
                    transparentDialog.dismiss();
                }
            }

XML file

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center">

    <ImageView style="@style/imageview"
        android:layout_marginTop="@dimen/_7sdp"
        android:src="@mipmap/ic_launcher"/>

    <EditText
        android:tag="@string/login_emailId_phone"
        android:layout_marginTop="@dimen/_12sdp"
        style="@style/edittext"
        android:drawableLeft="@drawable/user_icon"
        android:id="@+id/login_ed_emailPhone"
        android:inputType="text"/>

    <EditText
        android:tag="@string/login_password"
        android:layout_marginTop="@dimen/_12sdp"
        android:drawableLeft="@drawable/password_icon"
        android:id="@+id/login_ed_password"
        android:inputType="textPassword"
        android:hint="@string/login_password"
        style="@style/edittext"/>

    <TextView
        android:layout_marginTop="@dimen/_11sdp"
        android:id="@+id/login_tv_foregetPassword"
        android:text="@string/login_forgetPassword"
        style="@style/textView"
        android:textColor="#606060"
        android:textStyle="normal"/>

    <Button
        android:layout_marginTop="@dimen/_30sdp"
        android:id="@+id/login_bt_signin"
        style="@style/button"
        android:text="@string/login_singin"
        android:background="@drawable/big_green_btn_normal"
        />

    <cl.tempclick.ui.custom_view.LineThroughTextView
        android:layout_marginTop="@dimen/_12sdp"
        app:android_textColor="#606060"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:lineHeight="@dimen/_2sdp"
        app:lineColor="@color/colorGray"
        app:android_textSize="@dimen/_15sdp"
        app:android_text="@string/login_or"
        app:textPadding="@dimen/_10sdp"/>

    <Button
        android:layout_marginTop="@dimen/_12sdp"
        android:id="@+id/login_bt_linkedin"
        style="@style/button"
        android:text="@string/login_linkedin"
        android:background="@drawable/big_blue_btn_normal"
        />

    <TextView
        android:layout_marginTop="@dimen/_12sdp"
        android:id="@+id/login_tv_noAccount"
        android:text="@string/login_noAccount"
        style="@style/textView"
        android:textStyle="normal"
        android:textColor="#606060"
        android:layout_marginBottom="@dimen/_7sdp"/>

</LinearLayout>
<ViewStub
    android:id="@+id/login_vs_empty"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout="@layout/empty_view" />

like image 638
Reprator Avatar asked Nov 23 '15 05:11

Reprator


2 Answers

You should not be calling init() (or any code that touches the Android UI) in a non-UI thread.

like image 128
cybersam Avatar answered Oct 19 '22 12:10

cybersam


you must call textview getLayout() after the textview measure ,so it's better to call getLayout() in

textview.post(new Runnable() {     @Override     public void run() {         textview.getLayout()....     } }); 
like image 45
preqel Avatar answered Oct 19 '22 14:10

preqel