当前位置: 首页 > 知识库问答 >
问题:

尝试调用虚拟方法“int android”。文本布局getLineCount()'在空对象引用上

钱劲
2023-03-14

我随机得到空指针异常,通常它工作,有时它崩溃,我搜索了很多,但没有得到任何帮助,因为它没有正确的路线,我从哪里得到任何帮助,

我也在使用handler。

我的logcat错误如下,下面添加了代码,

 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)

这是我的代码如下,在这里它通常崩溃点击注册或忘记按钮第一次安装后,它通常工作正常,但有时它给我错误,

 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文件

<?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" />

共有3个答案

安奇
2023-03-14

我认为错误来自这一行

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

尝试注销你得到的索引值

林弘壮
2023-03-14

在textview测量之后,必须调用textviewgetLayout(),因此最好在中调用getLayout()

textview.post(new Runnable() {
    @Override
    public void run() {
        textview.getLayout()....
    }
});
夏侯瑞
2023-03-14

您不应该在非UI线程中调用init()(或任何接触Android UI的代码)。

 类似资料:
  • 我正在尝试实现一个外部色轮,它应该出现在的片段一直在崩溃我的应用程序。我想我明白为什么会发生这种情况,但是在尝试修复它大约6个小时后,我就要放弃了。我知道之前有人问过这个问题,但是我无法为我的特定问题导出一个修复程序。下面是我的代码: 这是Logcat错误: 如果有人能帮我解决这个问题,那就太好了。提前谢谢^^ 编辑:这是我的XML,按要求:

  • 我的应用程序有问题,我想解决它,但我无法访问解决方案,请帮助我,,,

  • 问题内容: 我收到以下错误 尝试在空对象引用上调用虚拟方法’void android.widget.StackView.setAdapter(android.widget.Adapter)’ 在这条线上 完整的片段 EventsFragment.java 是 Stack_Adapter.java Stack_Items 问题答案: 您正在执行: 你是。返回。 你为什么用? 在哪里?您应该从正确的x

  • 我的应用程序有问题,想解决它,但我无法访问解决方案,请帮帮我,,

  • 我正在尝试使用教程在应用程序中集成FireBase云消息: https://www.simplifiedcoding.net/firebase-cloud-messaging-tutorial-android/ 下面是logcat: 这是我的建筑格拉德尔: 注意:我的应用程序中没有应用程序模块。我只有一个建筑.梯度文件。 跟建筑有关吗?在官方站点中,他们说要在应用文件夹中复制json文件。不幸的是

  • 问题内容: 我尝试使用片段来打开数据库,但是,当我单击按钮开始搜索时,程序意外终止,并显示如下错误: 主片段: DBManager类: 顺便说一句,我在MainAcitivity中使用了有关DBManager的代码,并且成功了。将代码复制到上面的片段后,它失败了,该怎么办? 问题答案: 之前和之后你都做不到。 因为,您正在执行片段实例化时。该方法将始终返回null。另外,尽量不要将参考文献保留在您