web-dev-qa-db-ja.com

nullオブジェクト参照で仮想メソッド 'int Android.text.Layout.getLineCount()'を呼び出そうとしました

Nullポインターの例外がランダムに発生します。通常は機能し、クラッシュすることもあります。多くの検索を行いましたが、ヘルプが表示される適切な行がないため、ヘルプが表示されませんでした。

ハンドラーも使用しています。

私の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" />
28
Reprator

textviewメジャーの後にtextviewgetLayout()を呼び出す必要があるため、でgetLayout()を呼び出すことをお勧めします。

textview.post(new Runnable() {
    @Override
    public void run() {
        textview.getLayout()....
    }
});
0
preqel