尝试对null对象引用调用虚方法“int android.text.Layout.getLineCount()”

内容来源于 Stack Overflow,遵循 CC BY-SA 4.0 许可协议进行翻译与使用。IT领域专用引擎提供翻译支持

腾讯云小微IT领域专用引擎提供翻译支持

原文
Stack Overflow用户 修改于2018-06-08
  • 该问题已被编辑
  • 提问者: Stack Overflow用户
  • 提问时间: 2015-11-23 13:17

我是随机得到空指针异常,通常它工作,有时它崩溃,我已经搜索了很多,但没有得到任何帮助,因为它没有适当的行,我从哪里得到任何帮助,

我也对它使用了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);
                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);
                   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() {
                                            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"