问:
getActivity returning Null Pointer Exception when called from Fragment setUserVisibleHint
I have an app with Main Activity calling 3 fragments. I am seeing null pointer exception on app launch at the stage where getActivity is accessed from the first fragment.

```<code> E/AndroidRuntime: FATAL EXCEPTION: main Process: com.inc.sr, PID: 3019
 java.lang.NullPointerException: Attempt to invoke virtual method
 'android.support.v7.app.ActionBar
 com.inc.sr.MainActivity.getSupportActionBar()' on a null object
 reference
     at com.inc.sr.fragments.SRFrag.setUserVisibleHint(SRFrag.java:148)
     at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:136)
     at android.support.v4.view.ViewPager.populate(ViewPager.java:1234)
     at android.support.v4.view.ViewPager.populate(ViewPager.java:1084)
     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1614)
     at android.view.View.measure(View.java:18788)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:901)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
     at android.view.View.measure(View.java:18788) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
     at android.view.Choreographer.doCallbacks(Choreographer.java:670)
     at android.view.Choreographer.doFrame(Choreographer.java:606)
     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
     at android.os.Handler.handleCallback(Handler.java:739)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:148)
     at android.app.ActivityThread.main(ActivityThread.java:5417)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 12-04
 13:25:33.229 1261-2076/? E/SurfaceFlinger: ro.sf.lcd_density must be
 defined as a build property 12-04 13:25:33.237 3019-3042/com.inc.sr
 E/FA: Failed to send current screen to service 12-04 13:25:33.237
 3019-3042/com.inc.sr E/FA: Discarding data. Failed to send event to
 service 12-04 13:25:33.238 3019-3042/com.inc.sr E/FA: Failed to send
 current screen to service 12-04 13:26:22.703
 2452-2870/com.google.android.gms E/SQLiteCastStore: End saving paired
 guest mode devices 12-04 13:30:33.228 1634-3092/system_process
 E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb40be100 12-04
 13:30:33.239 1634-1645/system_process E/JavaBinder: !!! FAILED BINDER
 TRANSACTION !!!  (parcel size = 104) 12-04 13:30:33.244
 1634-1645/system_process E/JavaBinder: !!! FAILED BINDER TRANSACTION
 !!!  (parcel size = 104)
</code>```

Main Activity:

```<code>public class MainActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private CustomViewPager viewPager;
private MyAdapter mAdapter;
TextView mTitle;
String[] title = {"S screen", "Compare", "About US"};
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

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

    //FirebaseDatabase.getInstance().setPersistenceEnabled(true);

    if (findViewById(R.id.fragment_container) != null) {
        if (savedInstanceState != null) {
            return;
        }

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        //getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
        mTitle.setText(title[0]);

        mAdapter = new MyAdapter(getSupportFragmentManager());
        //viewPager = (ViewPager)findViewById(R.id.viewpager);
        viewPager = (CustomViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(mAdapter);
        viewPager.setPagingEnabled(false);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        tabLayout.getTabAt(0).setIcon(R.mipmap.searchs);
        tabLayout.getTabAt(1).setIcon(R.mipmap.compareu);
        tabLayout.getTabAt(2).setIcon(R.mipmap.infou);

        tabLayout.setOnTabSelectedListener(
                new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {

                    @Override
                    public void onTabSelected(TabLayout.Tab tab) {
                        super.onTabSelected(tab);
                        int pos = tab.getPosition();

                        switch (pos) {
                            case 0:
                                tabLayout.getTabAt(0).setIcon(R.mipmap.searchs);
                                break;
                            case 1:
                                tabLayout.getTabAt(1).setIcon(R.mipmap.compares);
                                break;
                            case 2:
                                tabLayout.getTabAt(2).setIcon(R.mipmap.infos);
                                break;
                        }
                    }

                    @Override
                    public void onTabUnselected(TabLayout.Tab tab) {
                        super.onTabUnselected(tab);
                        int pos = tab.getPosition();
                        switch (pos) {
                            case 0:
                                tabLayout.getTabAt(0).setIcon(R.mipmap.searchu);
                                break;
                            case 1:
                                tabLayout.getTabAt(1).setIcon(R.mipmap.compareu);
                                break;
                            case 2:
                                tabLayout.getTabAt(2).setIcon(R.mipmap.infou);
                                break;
                        }
                    }

                    @Override
                    public void onTabReselected(TabLayout.Tab tab) {
                        super.onTabReselected(tab);
                    }
                }
        );

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
                List<Fragment> fragments = fragmentManager.getFragments();
                if (fragments != null) {
                    for (Fragment fragment : fragments) {
                        if (fragment != null && fragment.isVisible()) {

                            switch (position) {
                                case 0:
                                    if (fragment.getClass().toString().contains("srFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                                        mTitle.setText(title[position]);
                                    } else if (fragment.getClass().toString().contains("sresFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                                        String state = fragment.getArguments().getString("STATES", "");
                                        String grade = fragment.getArguments().getString("GRADES", "");
                                        String title = state + " - " + grade + " Ranking";
                                        mTitle.setText(title);
                                    } else if (fragment.getClass().toString().contains("sdFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                                        String title = fragment.getArguments().getString("SCNAME", "");
                                        mTitle.setText(title);
                                    }
                                    break;
                                case 1:
                                    if (fragment.getClass().toString().contains("CompareFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                                        mTitle.setText(title[position]);
                                    } else if (fragment.getClass().toString().contains("CompareResultsFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                                        mTitle.setText("Compare Results");
                                    }
                                    break;
                                case 2:
                                    if (fragment.getClass().toString().contains("InfoFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                                        mTitle.setText(title[position]);
                                    }
                                    break;
                            }
                        }
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                System.out.println("AUTH FirebaseAuth onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                System.out.println("AUTH FirebaseAuth onAuthStateChanged:signed_out");
            }
        }
    };

    mAuth = FirebaseAuth.getInstance();

    mAuth.signInAnonymously()
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    System.out.println("AUTH FirebaseAuth signInAnonymously:onComplete:" + task.isSuccessful());

                    if (!task.isSuccessful()) {
                        System.out.println("AUTH FirebaseAuth signInAnonymously" + task.getException());

                    }
                }
            });

}

@Override
public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // handle arrow click here
    if (item.getItemId() == android.R.id.home) {
        //finish(); // close this activity and return to preview activity (if there is any)
        onBackPressed();
    }

    return super.onOptionsItemSelected(item);
}

public void onBackPressed() {
    if (viewPager.getCurrentItem() == 0) {
        if (mAdapter.getItem(0) instanceof sresFrag) {
            ((sresFrag) mAdapter.getItem(0)).backPressed();
        } else if (mAdapter.getItem(0) instanceof sdFrag) {
            ((sdFrag) mAdapter.getItem(0)).backPressed();
        } else {
            this.moveTaskToBack(true);
        }
    } else if (viewPager.getCurrentItem() == 1) {
        if (mAdapter.getItem(1) instanceof CompareResultsFrag) {
            ((CompareResultsFrag) mAdapter.getItem(1)).backPressed();
        } else if (mAdapter.getItem(1) instanceof CompareFrag) {
            viewPager.setCurrentItem(0);
        }
    } else if (viewPager.getCurrentItem() == 2) {
        if (mAdapter.getItem(2) instanceof InfoFrag) {
            viewPager.setCurrentItem(1);
        }
    }
}

private static class MyAdapter extends FragmentPagerAdapter {

    private final class FirstPageListener implements
            FirstPageFragmentListener {
        public void onSwitchToNextFragment(String year, String state, String grade, SchoolItem item, boolean backPressed) {
            mFragmentManager.beginTransaction().remove(mFragmentAtPos0)
                    .commit();
            if (mFragmentAtPos0 instanceof srFrag) {
                mFragmentAtPos0 = sresFrag.createInstance(FirstListener);
                Bundle args = new Bundle();
                args.putString("YEARS", year);
                args.putString("STATES", state);
                args.putString("GRADES", grade);
                mFragmentAtPos0.setArguments(args);
            } else if (mFragmentAtPos0 instanceof sresFrag && !(backPressed)) {
                mFragmentAtPos0 = sdFrag.createInstance(FirstListener);
                Bundle args = new Bundle();
                args.putString("YEARS", year);
                args.putString("STATES", state);
                args.putString("GRADES", grade);
                args.putSerializable("ITEM", item);
                args.putString("SCNAME", item.Name);
                mFragmentAtPos0.setArguments(args);
            } else if (mFragmentAtPos0 instanceof sdFrag && (backPressed)) {
                mFragmentAtPos0 = sresFrag.createInstance(FirstListener);
                Bundle args = new Bundle();
                System.out.println(year + state + grade);
                args.putString("YEARS", year);
                args.putString("STATES", state);
                args.putString("GRADES", grade);
                mFragmentAtPos0.setArguments(args);
            } else { // Instance of NextFragment
                mFragmentAtPos0 = srFrag.createInstance(FirstListener);
                System.out.println("UNI00 A");
            }

            notifyDataSetChanged();
        }
    }

    private final class SecondPageListener implements
            SecondPageFragmentListener {
        public void onSwitchToNextFragment(ArrayList<SchoolItem> schoolList, SchoolItem[] compareList, boolean backPressed) {
            mFragmentManager.beginTransaction().remove(mFragmentAtPos1)
                    .commit();
            if (mFragmentAtPos1 instanceof CompareFrag) {
                mFragmentAtPos1 = CompareResultsFrag.createInstance(SecondListener);
            } else { // Instance of NextFragment
                mFragmentAtPos1 = CompareFrag.createInstance(SecondListener);
            }

            Bundle args = new Bundle();
            args.putSerializable("SCLIST", schoolList);
            args.putSerializable("CMLIST", compareList);
            mFragmentAtPos1.setArguments(args);

            notifyDataSetChanged();
        }
    }

    private final class ThirdPageListener implements
            ThirdPageFragmentListener {
        public void onSwitchToNextFragment() {
            mFragmentManager.beginTransaction().remove(mFragmentAtPos2)
                    .commit();
            mFragmentAtPos2 = InfoFrag.createInstance(ThirdListener);

            notifyDataSetChanged();
        }
    }

    private String[] titles = {"Search", "Compare", " Info"};
    private final FragmentManager mFragmentManager;
    public Fragment mFragmentAtPos0;
    public Fragment mFragmentAtPos1;
    public Fragment mFragmentAtPos2;
    private Context context;
    FirstPageListener FirstListener = new FirstPageListener();
    SecondPageListener SecondListener = new SecondPageListener();
    ThirdPageListener ThirdListener = new ThirdPageListener();

    public MyAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
        mFragmentManager = fragmentManager;
        System.out.println("UNI00 B");
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0: // Fragment # 0
                if (mFragmentAtPos0 == null) {
                    //mFragmentAtPos0 = new OneFragment(listener);
                    mFragmentAtPos0 = srFrag.createInstance(FirstListener);
                    System.out.println("UNI00 1");
                }
                System.out.println(mFragmentAtPos0.toString());
                return mFragmentAtPos0;
            case 1: // Fragment # 1
                if (mFragmentAtPos1 == null) {
                    //mFragmentAtPos0 = new OneFragment(listener);
                    mFragmentAtPos1 = CompareFrag.createInstance(SecondListener);
                    System.out.println("UNI00 2");
                }
                //return new BuyMainFrag();
                return mFragmentAtPos1;
            case 2:// Fragment # 2
                if (mFragmentAtPos2 == null) {
                    //mFragmentAtPos0 = new OneFragment(listener);
                    mFragmentAtPos2 = InfoFrag.createInstance(ThirdListener);
                    System.out.println("UNI00 3");
                }
                return mFragmentAtPos2;
            //return new SellMainFrag();
        }
        System.out.println("UNI00 4");
        return null;
    }

    @Override
    public int getCount() {
        return titles.length;
    }

    @Override
    public int getItemPosition(Object object) {
        if (object instanceof srFrag &&
                mFragmentAtPos0 instanceof sresFrag) {
            return POSITION_NONE;
        }
        if (object instanceof sresFrag &&
                mFragmentAtPos0 instanceof srFrag) {
            return POSITION_NONE;
        }
        if (object instanceof sresFrag &&
                mFragmentAtPos0 instanceof sdFrag) {
            return POSITION_NONE;
        }
        if (object instanceof sdFrag &&
                mFragmentAtPos0 instanceof srFrag) {
            return POSITION_NONE;
        }
        if (object instanceof CompareFrag &&
                mFragmentAtPos1 instanceof CompareResultsFrag) {
            return POSITION_NONE;
        }
        if (object instanceof CompareResultsFrag &&
                mFragmentAtPos1 instanceof CompareFrag) {
            return POSITION_NONE;
        }
        if (object instanceof InfoFrag) {
            return POSITION_NONE;
        }
        return POSITION_UNCHANGED;
    }

}

public void setToolBarTitle(String title) {
    mTitle.setText(title);
}
}
</code>```

First Fragment:

```<code>public class srFrag extends Fragment {

Spinner spinnerYear, spinnerState, spinnerGrade;
static FirstPageFragmentListener firstPageListener;
private String year = "", state = "", grade = "";
String FragTitle = "s screen";
private SchoolItem notUsed;

public static srFrag createInstance(FirstPageFragmentListener listener) {
    srFrag frag = new srFrag();
    firstPageListener = listener;
    return frag;
}

public srFrag() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.s_r, container, false);

    spinnerYear = (Spinner) view.findViewById(R.id.spinnerYear);
    ArrayAdapter<CharSequence> adapterYear = ArrayAdapter
            .createFromResource(view.getContext(), R.array.year, R.layout.spinner_row);
    spinnerYear.setAdapter(adapterYear);

    spinnerState = (Spinner) view.findViewById(R.id.spinnerState);
    ArrayAdapter<CharSequence> adapterState = ArrayAdapter
            .createFromResource(view.getContext(), R.array.state, R.layout.spinner_row);
    spinnerState.setAdapter(adapterState);

    spinnerGrade = (Spinner) view.findViewById(R.id.spinnerGrade);
    ArrayAdapter<CharSequence> adapterGrade = ArrayAdapter
            .createFromResource(view.getContext(), R.array.grade, R.layout.spinner_row);
    spinnerGrade.setAdapter(adapterGrade);

    spinnerYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long arg3) {
            year = parent.getItemAtPosition(pos).toString();
            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("YEARS", year);
            editor.commit();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    spinnerState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long arg3) {
            state = parent.getItemAtPosition(pos).toString();
            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("STATES", state);
            editor.commit();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    spinnerGrade.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long arg3) {
            grade = parent.getItemAtPosition(pos).toString();
            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("GRADES", grade);
            editor.commit();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    Button button = (Button) view.findViewById(R.id.search_button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            firstPageListener.onSwitchToNextFragment(year, state, grade, notUsed, false);
        }
    });

    return view;
}

@Override
public void onResume() {
    super.onResume();
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser) {
        ((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false); //Null pointer exception thrown here
        ((MainActivity) getActivity()).setToolBarTitle(FragTitle);

    }
}
}
</code>```

答:
Yes, it will throw error coz it will call initially when your layout is not being loaded so you have to wait for some time,

This one is trick might help you

```<code>    @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser) {
new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                ((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false); //Null pointer exception thrown here
        ((MainActivity) getActivity()).setToolBarTitle(FragTitle);
            }
        }, 500);

    }
}
</code>```

Body:
I have an app with Main Activity calling 3 fragments. I am seeing null pointer exception on app launch at the stage where getActivity is accessed from the first fragment.

 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.inc.sr, PID: 3019
 java.lang.NullPointerException: Attempt to invoke virtual method
 'android.support.v7.app.ActionBar
 com.inc.sr.MainActivity.getSupportActionBar()' on a null object
 reference
     at com.inc.sr.fragments.SRFrag.setUserVisibleHint(SRFrag.java:148)
     at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:136)
     at android.support.v4.view.ViewPager.populate(ViewPager.java:1234)
     at android.support.v4.view.ViewPager.populate(ViewPager.java:1084)
     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1614)
     at android.view.View.measure(View.java:18788)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:901)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
     at android.view.View.measure(View.java:18788) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
     at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
     at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
     at android.view.View.measure(View.java:18788)
     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
     at android.view.Choreographer.doCallbacks(Choreographer.java:670)
     at android.view.Choreographer.doFrame(Choreographer.java:606)
     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
     at android.os.Handler.handleCallback(Handler.java:739)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:148)
     at android.app.ActivityThread.main(ActivityThread.java:5417)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 12-04
 13:25:33.229 1261-2076/? E/SurfaceFlinger: ro.sf.lcd_density must be
 defined as a build property 12-04 13:25:33.237 3019-3042/com.inc.sr
 E/FA: Failed to send current screen to service 12-04 13:25:33.237
 3019-3042/com.inc.sr E/FA: Discarding data. Failed to send event to
 service 12-04 13:25:33.238 3019-3042/com.inc.sr E/FA: Failed to send
 current screen to service 12-04 13:26:22.703
 2452-2870/com.google.android.gms E/SQLiteCastStore: End saving paired
 guest mode devices 12-04 13:30:33.228 1634-3092/system_process
 E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb40be100 12-04
 13:30:33.239 1634-1645/system_process E/JavaBinder: !!! FAILED BINDER
 TRANSACTION !!!  (parcel size = 104) 12-04 13:30:33.244
 1634-1645/system_process E/JavaBinder: !!! FAILED BINDER TRANSACTION
 !!!  (parcel size = 104)

Main Activity:

public class MainActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private CustomViewPager viewPager;
private MyAdapter mAdapter;
TextView mTitle;
String[] title = {"S screen", "Compare", "About US"};
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

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

    //FirebaseDatabase.getInstance().setPersistenceEnabled(true);

    if (findViewById(R.id.fragment_container) != null) {
        if (savedInstanceState != null) {
            return;
        }

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        //getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
        mTitle.setText(title[0]);

        mAdapter = new MyAdapter(getSupportFragmentManager());
        //viewPager = (ViewPager)findViewById(R.id.viewpager);
        viewPager = (CustomViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(mAdapter);
        viewPager.setPagingEnabled(false);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        tabLayout.getTabAt(0).setIcon(R.mipmap.searchs);
        tabLayout.getTabAt(1).setIcon(R.mipmap.compareu);
        tabLayout.getTabAt(2).setIcon(R.mipmap.infou);

        tabLayout.setOnTabSelectedListener(
                new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {

                    @Override
                    public void onTabSelected(TabLayout.Tab tab) {
                        super.onTabSelected(tab);
                        int pos = tab.getPosition();

                        switch (pos) {
                            case 0:
                                tabLayout.getTabAt(0).setIcon(R.mipmap.searchs);
                                break;
                            case 1:
                                tabLayout.getTabAt(1).setIcon(R.mipmap.compares);
                                break;
                            case 2:
                                tabLayout.getTabAt(2).setIcon(R.mipmap.infos);
                                break;
                        }
                    }

                    @Override
                    public void onTabUnselected(TabLayout.Tab tab) {
                        super.onTabUnselected(tab);
                        int pos = tab.getPosition();
                        switch (pos) {
                            case 0:
                                tabLayout.getTabAt(0).setIcon(R.mipmap.searchu);
                                break;
                            case 1:
                                tabLayout.getTabAt(1).setIcon(R.mipmap.compareu);
                                break;
                            case 2:
                                tabLayout.getTabAt(2).setIcon(R.mipmap.infou);
                                break;
                        }
                    }

                    @Override
                    public void onTabReselected(TabLayout.Tab tab) {
                        super.onTabReselected(tab);
                    }
                }
        );

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
                List<Fragment> fragments = fragmentManager.getFragments();
                if (fragments != null) {
                    for (Fragment fragment : fragments) {
                        if (fragment != null && fragment.isVisible()) {

                            switch (position) {
                                case 0:
                                    if (fragment.getClass().toString().contains("srFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                                        mTitle.setText(title[position]);
                                    } else if (fragment.getClass().toString().contains("sresFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                                        String state = fragment.getArguments().getString("STATES", "");
                                        String grade = fragment.getArguments().getString("GRADES", "");
                                        String title = state + " - " + grade + " Ranking";
                                        mTitle.setText(title);
                                    } else if (fragment.getClass().toString().contains("sdFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                                        String title = fragment.getArguments().getString("SCNAME", "");
                                        mTitle.setText(title);
                                    }
                                    break;
                                case 1:
                                    if (fragment.getClass().toString().contains("CompareFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                                        mTitle.setText(title[position]);
                                    } else if (fragment.getClass().toString().contains("CompareResultsFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                                        mTitle.setText("Compare Results");
                                    }
                                    break;
                                case 2:
                                    if (fragment.getClass().toString().contains("InfoFrag")) {
                                        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                                        mTitle.setText(title[position]);
                                    }
                                    break;
                            }
                        }
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                System.out.println("AUTH FirebaseAuth onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                System.out.println("AUTH FirebaseAuth onAuthStateChanged:signed_out");
            }
        }
    };

    mAuth = FirebaseAuth.getInstance();

    mAuth.signInAnonymously()
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    System.out.println("AUTH FirebaseAuth signInAnonymously:onComplete:" + task.isSuccessful());

                    if (!task.isSuccessful()) {
                        System.out.println("AUTH FirebaseAuth signInAnonymously" + task.getException());

                    }
                }
            });

}

@Override
public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // handle arrow click here
    if (item.getItemId() == android.R.id.home) {
        //finish(); // close this activity and return to preview activity (if there is any)
        onBackPressed();
    }

    return super.onOptionsItemSelected(item);
}

public void onBackPressed() {
    if (viewPager.getCurrentItem() == 0) {
        if (mAdapter.getItem(0) instanceof sresFrag) {
            ((sresFrag) mAdapter.getItem(0)).backPressed();
        } else if (mAdapter.getItem(0) instanceof sdFrag) {
            ((sdFrag) mAdapter.getItem(0)).backPressed();
        } else {
            this.moveTaskToBack(true);
        }
    } else if (viewPager.getCurrentItem() == 1) {
        if (mAdapter.getItem(1) instanceof CompareResultsFrag) {
            ((CompareResultsFrag) mAdapter.getItem(1)).backPressed();
        } else if (mAdapter.getItem(1) instanceof CompareFrag) {
            viewPager.setCurrentItem(0);
        }
    } else if (viewPager.getCurrentItem() == 2) {
        if (mAdapter.getItem(2) instanceof InfoFrag) {
            viewPager.setCurrentItem(1);
        }
    }
}

private static class MyAdapter extends FragmentPagerAdapter {

    private final class FirstPageListener implements
            FirstPageFragmentListener {
        public void onSwitchToNextFragment(String year, String state, String grade, SchoolItem item, boolean backPressed) {
            mFragmentManager.beginTransaction().remove(mFragmentAtPos0)
                    .commit();
            if (mFragmentAtPos0 instanceof srFrag) {
                mFragmentAtPos0 = sresFrag.createInstance(FirstListener);
                Bundle args = new Bundle();
                args.putString("YEARS", year);
                args.putString("STATES", state);
                args.putString("GRADES", grade);
                mFragmentAtPos0.setArguments(args);
            } else if (mFragmentAtPos0 instanceof sresFrag && !(backPressed)) {
                mFragmentAtPos0 = sdFrag.createInstance(FirstListener);
                Bundle args = new Bundle();
                args.putString("YEARS", year);
                args.putString("STATES", state);
                args.putString("GRADES", grade);
                args.putSerializable("ITEM", item);
                args.putString("SCNAME", item.Name);
                mFragmentAtPos0.setArguments(args);
            } else if (mFragmentAtPos0 instanceof sdFrag && (backPressed)) {
                mFragmentAtPos0 = sresFrag.createInstance(FirstListener);
                Bundle args = new Bundle();
                System.out.println(year + state + grade);
                args.putString("YEARS", year);
                args.putString("STATES", state);
                args.putString("GRADES", grade);
                mFragmentAtPos0.setArguments(args);
            } else { // Instance of NextFragment
                mFragmentAtPos0 = srFrag.createInstance(FirstListener);
                System.out.println("UNI00 A");
            }

            notifyDataSetChanged();
        }
    }

    private final class SecondPageListener implements
            SecondPageFragmentListener {
        public void onSwitchToNextFragment(ArrayList<SchoolItem> schoolList, SchoolItem[] compareList, boolean backPressed) {
            mFragmentManager.beginTransaction().remove(mFragmentAtPos1)
                    .commit();
            if (mFragmentAtPos1 instanceof CompareFrag) {
                mFragmentAtPos1 = CompareResultsFrag.createInstance(SecondListener);
            } else { // Instance of NextFragment
                mFragmentAtPos1 = CompareFrag.createInstance(SecondListener);
            }

            Bundle args = new Bundle();
            args.putSerializable("SCLIST", schoolList);
            args.putSerializable("CMLIST", compareList);
            mFragmentAtPos1.setArguments(args);

            notifyDataSetChanged();
        }
    }

    private final class ThirdPageListener implements
            ThirdPageFragmentListener {
        public void onSwitchToNextFragment() {
            mFragmentManager.beginTransaction().remove(mFragmentAtPos2)
                    .commit();
            mFragmentAtPos2 = InfoFrag.createInstance(ThirdListener);

            notifyDataSetChanged();
        }
    }

    private String[] titles = {"Search", "Compare", " Info"};
    private final FragmentManager mFragmentManager;
    public Fragment mFragmentAtPos0;
    public Fragment mFragmentAtPos1;
    public Fragment mFragmentAtPos2;
    private Context context;
    FirstPageListener FirstListener = new FirstPageListener();
    SecondPageListener SecondListener = new SecondPageListener();
    ThirdPageListener ThirdListener = new ThirdPageListener();

    public MyAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
        mFragmentManager = fragmentManager;
        System.out.println("UNI00 B");
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0: // Fragment # 0
                if (mFragmentAtPos0 == null) {
                    //mFragmentAtPos0 = new OneFragment(listener);
                    mFragmentAtPos0 = srFrag.createInstance(FirstListener);
                    System.out.println("UNI00 1");
                }
                System.out.println(mFragmentAtPos0.toString());
                return mFragmentAtPos0;
            case 1: // Fragment # 1
                if (mFragmentAtPos1 == null) {
                    //mFragmentAtPos0 = new OneFragment(listener);
                    mFragmentAtPos1 = CompareFrag.createInstance(SecondListener);
                    System.out.println("UNI00 2");
                }
                //return new BuyMainFrag();
                return mFragmentAtPos1;
            case 2:// Fragment # 2
                if (mFragmentAtPos2 == null) {
                    //mFragmentAtPos0 = new OneFragment(listener);
                    mFragmentAtPos2 = InfoFrag.createInstance(ThirdListener);
                    System.out.println("UNI00 3");
                }
                return mFragmentAtPos2;
            //return new SellMainFrag();
        }
        System.out.println("UNI00 4");
        return null;
    }

    @Override
    public int getCount() {
        return titles.length;
    }

    @Override
    public int getItemPosition(Object object) {
        if (object instanceof srFrag &&
                mFragmentAtPos0 instanceof sresFrag) {
            return POSITION_NONE;
        }
        if (object instanceof sresFrag &&
                mFragmentAtPos0 instanceof srFrag) {
            return POSITION_NONE;
        }
        if (object instanceof sresFrag &&
                mFragmentAtPos0 instanceof sdFrag) {
            return POSITION_NONE;
        }
        if (object instanceof sdFrag &&
                mFragmentAtPos0 instanceof srFrag) {
            return POSITION_NONE;
        }
        if (object instanceof CompareFrag &&
                mFragmentAtPos1 instanceof CompareResultsFrag) {
            return POSITION_NONE;
        }
        if (object instanceof CompareResultsFrag &&
                mFragmentAtPos1 instanceof CompareFrag) {
            return POSITION_NONE;
        }
        if (object instanceof InfoFrag) {
            return POSITION_NONE;
        }
        return POSITION_UNCHANGED;
    }

}

public void setToolBarTitle(String title) {
    mTitle.setText(title);
}
}

First Fragment:

public class srFrag extends Fragment {

Spinner spinnerYear, spinnerState, spinnerGrade;
static FirstPageFragmentListener firstPageListener;
private String year = "", state = "", grade = "";
String FragTitle = "s screen";
private SchoolItem notUsed;

public static srFrag createInstance(FirstPageFragmentListener listener) {
    srFrag frag = new srFrag();
    firstPageListener = listener;
    return frag;
}

public srFrag() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.s_r, container, false);

    spinnerYear = (Spinner) view.findViewById(R.id.spinnerYear);
    ArrayAdapter<CharSequence> adapterYear = ArrayAdapter
            .createFromResource(view.getContext(), R.array.year, R.layout.spinner_row);
    spinnerYear.setAdapter(adapterYear);

    spinnerState = (Spinner) view.findViewById(R.id.spinnerState);
    ArrayAdapter<CharSequence> adapterState = ArrayAdapter
            .createFromResource(view.getContext(), R.array.state, R.layout.spinner_row);
    spinnerState.setAdapter(adapterState);

    spinnerGrade = (Spinner) view.findViewById(R.id.spinnerGrade);
    ArrayAdapter<CharSequence> adapterGrade = ArrayAdapter
            .createFromResource(view.getContext(), R.array.grade, R.layout.spinner_row);
    spinnerGrade.setAdapter(adapterGrade);

    spinnerYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long arg3) {
            year = parent.getItemAtPosition(pos).toString();
            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("YEARS", year);
            editor.commit();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    spinnerState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long arg3) {
            state = parent.getItemAtPosition(pos).toString();
            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("STATES", state);
            editor.commit();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    spinnerGrade.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long arg3) {
            grade = parent.getItemAtPosition(pos).toString();
            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("GRADES", grade);
            editor.commit();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    Button button = (Button) view.findViewById(R.id.search_button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            firstPageListener.onSwitchToNextFragment(year, state, grade, notUsed, false);
        }
    });

    return view;
}

@Override
public void onResume() {
    super.onResume();
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser) {
        ((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false); //Null pointer exception thrown here
        ((MainActivity) getActivity()).setToolBarTitle(FragTitle);

    }
}
}

Body:
Yes, it will throw error coz it will call initially when your layout is not being loaded so you have to wait for some time,

This one is trick might help you

    @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser) {
new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                ((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false); //Null pointer exception thrown here
        ((MainActivity) getActivity()).setToolBarTitle(FragTitle);
            }
        }, 500);

    }
}


来源: stackexchange

问:
Count no of records as per the date from table and format the date using PHP and MySQL
I need to etch no of records as per the date filed and after fetching the data I need to format the date using PHP and MySQL. I am explaining my table below.

db_audit:

```<code>id        auditname         date
 1          xxxx            2017-12-01 12:26:49
 2          sss             2017-12-01 12:20:00
 3         fff              2017-12-01 12:00:00
 4        hhh              2017-12-02 12:27:49
 5        ttt              2017-12-02 11:26:49
 6       yyy               2017-12-03 10:26:49
</code>```

Here I need to fetch no of records as per the date only. Here for 2017-12-01 there are 3 records present. I need to push all data into an array like this key format {'no_records'=>3,'date'=>2017-12-01}. Here also I need to formatted the database date field value from 2017-12-03 10:26:49 to 2017-12-03 and it should be in string format. Here I need the query to retrieve these type of value.

答:
```<code>SELECT count(`id`) as no_records, DATE(`date`) as date FROM tableName GROUP BY DATE(`date`);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to etch no of records as per the date filed and after fetching the data I need to format the date using PHP and MySQL. I am explaining my table below.

db_audit:

id        auditname         date
 1          xxxx            2017-12-01 12:26:49
 2          sss             2017-12-01 12:20:00
 3         fff              2017-12-01 12:00:00
 4        hhh              2017-12-02 12:27:49
 5        ttt              2017-12-02 11:26:49
 6       yyy               2017-12-03 10:26:49

Here I need to fetch no of records as per the date only. Here for 2017-12-01 there are 3 records present. I need to push all data into an array like this key format {'no_records'=>3,'date'=>2017-12-01}. Here also I need to formatted the database date field value from 2017-12-03 10:26:49 to 2017-12-03 and it should be in string format. Here I need the query to retrieve these type of value.


问:
Unable to click on a button due to incorrect position in UI Automatorviewer
UI Automator Viewer

Whenever I use below command to click on Ok button, it clicks on the same position as pointing in UI Automator viewer. (screenshot)

I need to click on Ok Button.

```<code>Driver.findElement(By.xpath("//android.widget.Button[@text='Ok']")).click();
</code>```

答:
The problem was when i am trying enter data on signup page Keyboards opens and due to that UI Automator screenshot giving wrong position of button. So what i have done is to use below command to hide the keyboard before clicking signup button.</p>

```<code>Driver.navigate().back();
delay(3000);
Driver.findElement(By.id("btn_register_signup")).click();
</code>```

Body:
UI Automator Viewer

Whenever I use below command to click on Ok button, it clicks on the same position as pointing in UI Automator viewer. (screenshot)

I need to click on Ok Button.

Driver.findElement(By.xpath("//android.widget.Button[@text='Ok']")).click();

Body:
The problem was when i am trying enter data on signup page Keyboards opens and due to that UI Automator screenshot giving wrong position of button. So what i have done is to use below command to hide the keyboard before clicking signup button.

Driver.navigate().back();
delay(3000);
Driver.findElement(By.id("btn_register_signup")).click();


问:
openssl rsautl "unable to load Public Key"
I generated an RSA public key in PKCS#1 RSAPublicKey format. I want to encrypt some data with openssl rsautl using this key, like so:

```<code>$ openssl genrsa -out private_key.pem 512
Generating RSA private key, 512 bit long modulus
................++++++++++++
...++++++++++++
e is 65537 (0x10001)
$ openssl rsa -in private_key.pem -RSAPublicKey_out -out public_key.pem
writing RSA key
$ echo "this is the cleartext" | openssl rsautl -encrypt -out encrypted_with_pub_key -pubin -inkey public_key.pem
unable to load Public Key
</code>```

What is going on here? Why is openssl unable to read a key which it itself generated? What formats can it read? And more generally, why is this so poorly documented?

答:
TL;DR: OpenSSL supports several legacy formats that are deprecated.  It seems there is a special case for openssl rsa -pubout when the input is an RSA private key pair.  At the end, I give two sequences of commands that let the OP's encrypt (and a corresponding decrypt) succeed; one by using DER rather than PEM, and another by first emitting DER, then converting it to PEM...strangely enough, using openssl rsa, which outputs the modern format when the input is a DER-encoded public key... go figure.  Anyway, below is a long description of why the OP's initial attempt failed.  As for "why so poorly documented"...welcome to OpenSSL.  Learn the source directory structure well, as it will speed up your grepping. :)

A long explanation (details taken from OpenSSL 1.0.2m)

The OpenSSL rsautl app defaults the -inform argument (incoming key representation) to format = FORMAT_PEM.

It then selects the reader for the incoming key using the format as follows:

```<code>else if (format == FORMAT_PEMRSA) {
    RSA *rsa;
    rsa = PEM_read_bio_RSAPublicKey(key, NULL,
                                    (pem_password_cb *)password_callback,
                                    &cb_data);
    /* ... */
}
else if (format == FORMAT_PEM) {
    pkey = PEM_read_bio_PUBKEY(key, NULL,
                               (pem_password_cb *)password_callback,
                               &cb_data);
</code>```

So, we'll be using PEM_read_bio_PUBKEY.  Note the entry for FORMAT_PEMRSA above it...we'll develop the path that leads to PEM_read_bio_RSAPublicKey at the same time.  Both of these readers are defined via a few macros

```<code>crypto/pem/pem_all.c:427:IMPLEMENT_PEM_rw(PUBKEY, EVP_PKEY, PEM_STRING_PUBLIC, PUBKEY)
crypto/pem/pem_all.c:241:IMPLEMENT_PEM_rw_const(RSAPublicKey, RSA, PEM_STRING_RSA_PUBLIC, RSAPublicKey)
</code>```

Which expand to

```<code># define IMPLEMENT_PEM_rw(name, type, str, asn1) \
    IMPLEMENT_PEM_read(name, type, str, asn1) \
    IMPLEMENT_PEM_write(name, type, str, asn1)

# define IMPLEMENT_PEM_rw_const(name, type, str, asn1) \
    IMPLEMENT_PEM_read(name, type, str, asn1) \
    IMPLEMENT_PEM_write_const(name, type, str, asn1)
</code>```

That in turn use

```<code># define IMPLEMENT_PEM_read(name, type, str, asn1) \
    IMPLEMENT_PEM_read_bio(name, type, str, asn1) \
    IMPLEMENT_PEM_read_fp(name, type, str, asn1)
</code>```

Which builds the actual definition as:

```<code># define IMPLEMENT_PEM_read_bio(name, type, str, asn1) \
type *PEM_read_bio_##name(BIO *bp, type **x, pem_password_cb *cb, void *u)\
{ \
  return PEM_ASN1_read_bio((d2i_of_void *)d2i_##asn1, str,bp,(void **)x,cb,u); \
}
</code>```

Of particular note is the 3rd argument, str which is passed as PEM_STRING_PUBLIC for the PEM_read_bio_PUBKEY version, and as PEM_STRING_RSA_PUBLIC for the PEM_read_bio_RsaPublicKey version.  These strings are, respectively,

```<code>./crypto/pem/pem.h:122:# define PEM_STRING_PUBLIC       "PUBLIC KEY"
./crypto/pem/pem.h:124:# define PEM_STRING_RSA_PUBLIC   "RSA PUBLIC KEY"
</code>```

Looking into the implementation of PEM_ASN1_read_bio, we see it calls PEM_bytes_read_bio

```<code>void *PEM_ASN1_read_bio(d2i_of_void *d2i, const char *name, BIO *bp, void **x,
                        pem_password_cb *cb, void *u)
{
    const unsigned char *p = NULL;
    unsigned char *data = NULL;
    long len;
    char *ret = NULL;

    if (!PEM_bytes_read_bio(&data, &len, NULL, name, bp, cb, u))
        return NULL;
    /* ... */
</code>```

PEM_bytes_read_bio reads the key file, breaking it into portions. nm gets the marker between ----- secions, e.g.,-----BEGIN RSA PUBLIC KEY-----, which is then checked by check_pem.

```<code>int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
                       const char *name, BIO *bp, pem_password_cb *cb,
                       void *u)
{
    EVP_CIPHER_INFO cipher;
    char *nm = NULL, *header = NULL;
    unsigned char *data = NULL;
    long len;
    int ret = 0;

    for (;;) {
        if (!PEM_read_bio(bp, &nm, &header, &data, &len)) {
            if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
                ERR_add_error_data(2, "Expecting: ", name);
            return 0;
        }
        if (check_pem(nm, name))
</code>```

And check_pem checks as follows, where nm is the string found in the file, and name was passed from where it is hard-coded in the PEM_read_bio_XXX function.

```<code>static int check_pem(const char *nm, const char *name)
{
    /* Normal matching nm and name */
    if (!strcmp(nm, name))
        return 1;

    /* special cases for
      PKCS8 format (BEGIN PRIVATE KEY or BEGIN ENCRYPTED PRIVATE KEY)
      Various things ending in PARAMETERS
      Various X509 related files
      PKCS7 format (BEGIN PKCS7 or BEGIN PKCS7 SIGNED DATA)
      CMS things (BEGIN CMS) */

    /* ... */
</code>```

It just does a strcmp between name and nm.  So, to successfully read the RSA public key with PEM_read_bio_PUBKEY, it needs to start with -----BEGIN PUBLIC KEY-----...but looking at the key produced by the OP's instructions, we find -----BEGIN RSA PUBLIC KEY-----.  But that's the string that corresponds to PEM_read_bio_RsaPublicKey...  Maybe we can use -inform to select format = FORMAT_PEMRSA instead, and get rsautl to read our public key that way.  rsautl uses a function called str2fmt to parse the -inform argument.  Let's take a look:

```<code>int str2fmt(char *s)
{
    if (s == NULL)
        return FORMAT_UNDEF;
    if ((*s == 'D') || (*s == 'd'))
        return (FORMAT_ASN1);
    else if ((*s == 'T') || (*s == 't'))
        return (FORMAT_TEXT);
    else if ((*s == 'N') || (*s == 'n'))
        return (FORMAT_NETSCAPE);
    else if ((*s == 'S') || (*s == 's'))
        return (FORMAT_SMIME);
    else if ((*s == 'M') || (*s == 'm'))
        return (FORMAT_MSBLOB);
    else if ((*s == '1')
             || (strcmp(s, "PKCS12") == 0) || (strcmp(s, "pkcs12") == 0)
             || (strcmp(s, "P12") == 0) || (strcmp(s, "p12") == 0))
        return (FORMAT_PKCS12);
    else if ((*s == 'E') || (*s == 'e'))
        return (FORMAT_ENGINE);
    else if ((*s == 'H') || (*s == 'h'))
        return FORMAT_HTTP;
    else if ((*s == 'P') || (*s == 'p')) {
        if (s[1] == 'V' || s[1] == 'v')
            return FORMAT_PVK;
        else
            return (FORMAT_PEM);
    } else
        return (FORMAT_UNDEF);
}
</code>```

Nope.  There's no way to make it return FORMAT_PEMRSA.

Well, what if we edit the public key file to make the markers say -----BEGIN PUBLIC KEY----- instead?

```<code>$ sed -e "s/RSA PUBLIC/PUBLIC/" public_key.pem > public_key_mod.pem
$ echo "this is the cleartext" | openssl rsautl -encrypt -out encrypted_with_pub_key -pubin -inkey public_key_mod.pem
unable to load Public Key
</code>```

Nope.

What if we extract the public key to DER instead of PEM?

```<code>$ openssl rsa -in private_key.pem -out public_key.der -outform DER -pubout
writing RSA key
$ echo "this is the cleartext" | openssl rsautl -encrypt -out encrypted_with_pub_key -pubin -inkey public_key.der -keyform DER

$ openssl rsautl  -decrypt -in encrypted_with_pub_key -inkey private_key.pem
this is the cleartext
</code>```

Success!  Maybe we can get OpenSSL to convert the DER key into a form compatible with rsautl

```<code>$ openssl rsa -in public_key.der -inform DER -pubin -out test.pem
writing RSA key
$ cat test.pem
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM3uGdU6YtwI5S8K+GgddW8KhrzmSFVI
6cvBT+XqOuSVo+n8VyUfADHw4rPxjy/dWDpyOxzWdTg8VZ77Vs06af8CAwEAAQ==
-----END PUBLIC KEY-----
$ echo "this is the cleartext" | openssl rsautl -encrypt -out encrypted_with_pub_key -pubin -inkey test.pem

$ openssl rsautl  -decrypt -in encrypted_with_pub_key -inkey private_key.pem
this is the cleartext
</code>```

So yes...it looks like openssl rsa only writes the obsolete BEGIN RSA PUBLIC KEY form when it takes a BEGIN RSA PRIVATE KEY as input.

Body:
I generated an RSA public key in PKCS#1 RSAPublicKey format. I want to encrypt some data with openssl rsautl using this key, like so:

$ openssl genrsa -out private_key.pem 512
Generating RSA private key, 512 bit long modulus
................++++++++++++
...++++++++++++
e is 65537 (0x10001)
$ openssl rsa -in private_key.pem -RSAPublicKey_out -out public_key.pem
writing RSA key
$ echo "this is the cleartext" | openssl rsautl -encrypt -out encrypted_with_pub_key -pubin -inkey public_key.pem
unable to load Public Key

What is going on here? Why is openssl unable to read a key which it itself generated? What formats can it read? And more generally, why is this so poorly documented?

Body:
TL;DR: OpenSSL supports several legacy formats that are deprecated.  It seems there is a special case for openssl rsa -pubout when the input is an RSA private key pair.  At the end, I give two sequences of commands that let the OP's encrypt (and a corresponding decrypt) succeed; one by using DER rather than PEM, and another by first emitting DER, then converting it to PEM...strangely enough, using openssl rsa, which outputs the modern format when the input is a DER-encoded public key... go figure.  Anyway, below is a long description of why the OP's initial attempt failed.  As for "why so poorly documented"...welcome to OpenSSL.  Learn the source directory structure well, as it will speed up your grepping. :)

A long explanation (details taken from OpenSSL 1.0.2m)

The OpenSSL rsautl app defaults the -inform argument (incoming key representation) to format = FORMAT_PEM.

It then selects the reader for the incoming key using the format as follows:

else if (format == FORMAT_PEMRSA) {
    RSA *rsa;
    rsa = PEM_read_bio_RSAPublicKey(key, NULL,
                                    (pem_password_cb *)password_callback,
                                    &cb_data);
    /* ... */
}
else if (format == FORMAT_PEM) {
    pkey = PEM_read_bio_PUBKEY(key, NULL,
                               (pem_password_cb *)password_callback,
                               &cb_data);

So, we'll be using PEM_read_bio_PUBKEY.  Note the entry for FORMAT_PEMRSA above it...we'll develop the path that leads to PEM_read_bio_RSAPublicKey at the same time.  Both of these readers are defined via a few macros

crypto/pem/pem_all.c:427:IMPLEMENT_PEM_rw(PUBKEY, EVP_PKEY, PEM_STRING_PUBLIC, PUBKEY)
crypto/pem/pem_all.c:241:IMPLEMENT_PEM_rw_const(RSAPublicKey, RSA, PEM_STRING_RSA_PUBLIC, RSAPublicKey)

Which expand to

# define IMPLEMENT_PEM_rw(name, type, str, asn1) \
    IMPLEMENT_PEM_read(name, type, str, asn1) \
    IMPLEMENT_PEM_write(name, type, str, asn1)

# define IMPLEMENT_PEM_rw_const(name, type, str, asn1) \
    IMPLEMENT_PEM_read(name, type, str, asn1) \
    IMPLEMENT_PEM_write_const(name, type, str, asn1)

That in turn use

# define IMPLEMENT_PEM_read(name, type, str, asn1) \
    IMPLEMENT_PEM_read_bio(name, type, str, asn1) \
    IMPLEMENT_PEM_read_fp(name, type, str, asn1)

Which builds the actual definition as:

# define IMPLEMENT_PEM_read_bio(name, type, str, asn1) \
type *PEM_read_bio_##name(BIO *bp, type **x, pem_password_cb *cb, void *u)\
{ \
  return PEM_ASN1_read_bio((d2i_of_void *)d2i_##asn1, str,bp,(void **)x,cb,u); \
}

Of particular note is the 3rd argument, str which is passed as PEM_STRING_PUBLIC for the PEM_read_bio_PUBKEY version, and as PEM_STRING_RSA_PUBLIC for the PEM_read_bio_RsaPublicKey version.  These strings are, respectively,

./crypto/pem/pem.h:122:# define PEM_STRING_PUBLIC       "PUBLIC KEY"
./crypto/pem/pem.h:124:# define PEM_STRING_RSA_PUBLIC   "RSA PUBLIC KEY"

Looking into the implementation of PEM_ASN1_read_bio, we see it calls PEM_bytes_read_bio

void *PEM_ASN1_read_bio(d2i_of_void *d2i, const char *name, BIO *bp, void **x,
                        pem_password_cb *cb, void *u)
{
    const unsigned char *p = NULL;
    unsigned char *data = NULL;
    long len;
    char *ret = NULL;

    if (!PEM_bytes_read_bio(&data, &len, NULL, name, bp, cb, u))
        return NULL;
    /* ... */

PEM_bytes_read_bio reads the key file, breaking it into portions. nm gets the marker between ----- secions, e.g.,-----BEGIN RSA PUBLIC KEY-----, which is then checked by check_pem.

int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
                       const char *name, BIO *bp, pem_password_cb *cb,
                       void *u)
{
    EVP_CIPHER_INFO cipher;
    char *nm = NULL, *header = NULL;
    unsigned char *data = NULL;
    long len;
    int ret = 0;

    for (;;) {
        if (!PEM_read_bio(bp, &nm, &header, &data, &len)) {
            if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
                ERR_add_error_data(2, "Expecting: ", name);
            return 0;
        }
        if (check_pem(nm, name))

And check_pem checks as follows, where nm is the string found in the file, and name was passed from where it is hard-coded in the PEM_read_bio_XXX function.

static int check_pem(const char *nm, const char *name)
{
    /* Normal matching nm and name */
    if (!strcmp(nm, name))
        return 1;

    /* special cases for
      PKCS8 format (BEGIN PRIVATE KEY or BEGIN ENCRYPTED PRIVATE KEY)
      Various things ending in PARAMETERS
      Various X509 related files
      PKCS7 format (BEGIN PKCS7 or BEGIN PKCS7 SIGNED DATA)
      CMS things (BEGIN CMS) */

    /* ... */

It just does a strcmp between name and nm.  So, to successfully read the RSA public key with PEM_read_bio_PUBKEY, it needs to start with -----BEGIN PUBLIC KEY-----...but looking at the key produced by the OP's instructions, we find -----BEGIN RSA PUBLIC KEY-----.  But that's the string that corresponds to PEM_read_bio_RsaPublicKey...  Maybe we can use -inform to select format = FORMAT_PEMRSA instead, and get rsautl to read our public key that way.  rsautl uses a function called str2fmt to parse the -inform argument.  Let's take a look:

int str2fmt(char *s)
{
    if (s == NULL)
        return FORMAT_UNDEF;
    if ((*s == 'D') || (*s == 'd'))
        return (FORMAT_ASN1);
    else if ((*s == 'T') || (*s == 't'))
        return (FORMAT_TEXT);
    else if ((*s == 'N') || (*s == 'n'))
        return (FORMAT_NETSCAPE);
    else if ((*s == 'S') || (*s == 's'))
        return (FORMAT_SMIME);
    else if ((*s == 'M') || (*s == 'm'))
        return (FORMAT_MSBLOB);
    else if ((*s == '1')
             || (strcmp(s, "PKCS12") == 0) || (strcmp(s, "pkcs12") == 0)
             || (strcmp(s, "P12") == 0) || (strcmp(s, "p12") == 0))
        return (FORMAT_PKCS12);
    else if ((*s == 'E') || (*s == 'e'))
        return (FORMAT_ENGINE);
    else if ((*s == 'H') || (*s == 'h'))
        return FORMAT_HTTP;
    else if ((*s == 'P') || (*s == 'p')) {
        if (s[1] == 'V' || s[1] == 'v')
            return FORMAT_PVK;
        else
            return (FORMAT_PEM);
    } else
        return (FORMAT_UNDEF);
}

Nope.  There's no way to make it return FORMAT_PEMRSA.

Well, what if we edit the public key file to make the markers say -----BEGIN PUBLIC KEY----- instead?

$ sed -e "s/RSA PUBLIC/PUBLIC/" public_key.pem > public_key_mod.pem
$ echo "this is the cleartext" | openssl rsautl -encrypt -out encrypted_with_pub_key -pubin -inkey public_key_mod.pem
unable to load Public Key

Nope.

What if we extract the public key to DER instead of PEM?

$ openssl rsa -in private_key.pem -out public_key.der -outform DER -pubout
writing RSA key
$ echo "this is the cleartext" | openssl rsautl -encrypt -out encrypted_with_pub_key -pubin -inkey public_key.der -keyform DER

$ openssl rsautl  -decrypt -in encrypted_with_pub_key -inkey private_key.pem
this is the cleartext

Success!  Maybe we can get OpenSSL to convert the DER key into a form compatible with rsautl

$ openssl rsa -in public_key.der -inform DER -pubin -out test.pem
writing RSA key
$ cat test.pem
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM3uGdU6YtwI5S8K+GgddW8KhrzmSFVI
6cvBT+XqOuSVo+n8VyUfADHw4rPxjy/dWDpyOxzWdTg8VZ77Vs06af8CAwEAAQ==
-----END PUBLIC KEY-----
$ echo "this is the cleartext" | openssl rsautl -encrypt -out encrypted_with_pub_key -pubin -inkey test.pem

$ openssl rsautl  -decrypt -in encrypted_with_pub_key -inkey private_key.pem
this is the cleartext

So yes...it looks like openssl rsa only writes the obsolete BEGIN RSA PUBLIC KEY form when it takes a BEGIN RSA PRIVATE KEY as input.


问:
Java Brains struts 2 project is not running though the code is same as the tutorial
I'm learning struts 2 from Java Brains. I've written a simple Hello world type struts 2 web application. It just shows an success page or error page. I've done everything instructed in the tutorial, but unfortunately the page is not loading. Following is the project explorer.

I've edited web.xml file like below.

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts 2 Web Application</display-name>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
</code>```

According to the tutorial, above web.xml configuration handovers the whole request response process to struts. I've configured struts.xml file like following.

```<code><?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <package name="default" extends="struts-default">
        <action name="getTutorial" class="action.TutorialAction">
            <result name="success">/success.jsp</result>
            <result name="failure">/error.jsp</result>
        </action>
    </package>
</struts>
</code>```

I've written action.TutorialAction class like following.

```<code>package action;

public class TutorialAction {
    public String execute(){
        System.out.println("Hello From execute");
        return "success";
    }
}
</code>```

After running the project under Tomcat 7, the url "http://localhost:8080/Struts2Starter/getTutorial.action" should load success.jsp page. But it's showing 404 error.

success.jsp page is just a .jsp page.

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Success Page
</body>
</html>
</code>```

I'm clueless why it's not running. I've been banging my head to solve it for a week and at last it just no hope :( . Help me please,  Thanks in advance.

答:
Please see the following points carefully:

1) You must add all the jar files of struts2 which is easily avaliable on "javatpoint".

2) Run it with only getTutorial instead of getTutorial.action, like "http://localhost:8080/Struts2Starter/getTutorial" sometimes its work.
You can also watch Java video's from here
https://www.youtube.com/channel/UCWJ9QB_Ng-dgEOFd_1Ouobg

Body:
I'm learning struts 2 from Java Brains. I've written a simple Hello world type struts 2 web application. It just shows an success page or error page. I've done everything instructed in the tutorial, but unfortunately the page is not loading. Following is the project explorer.

I've edited web.xml file like below.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts 2 Web Application</display-name>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

According to the tutorial, above web.xml configuration handovers the whole request response process to struts. I've configured struts.xml file like following.

<?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <package name="default" extends="struts-default">
        <action name="getTutorial" class="action.TutorialAction">
            <result name="success">/success.jsp</result>
            <result name="failure">/error.jsp</result>
        </action>
    </package>
</struts>

I've written action.TutorialAction class like following.

package action;

public class TutorialAction {
    public String execute(){
        System.out.println("Hello From execute");
        return "success";
    }
}

After running the project under Tomcat 7, the url "http://localhost:8080/Struts2Starter/getTutorial.action" should load success.jsp page. But it's showing 404 error.

success.jsp page is just a .jsp page.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

Success Page

I'm clueless why it's not running. I've been banging my head to solve it for a week and at last it just no hope :( . Help me please,  Thanks in advance.


问:
Com ports are not detected with jSSC
I'm trying to implement the transfering data with the help of Com ports in my java application. Firstly I decided to create SerialPort object like this.

```<code> SerialPort serialPort = new SerialPort("COM1");

 try {
        serialPort.openPort();
 } catch (SerialPortException ex) {
        ex.printStackTrace();
 }
</code>```

However there was an jssc.SerialPortException: Port name - COM1; Method name - openPort(); Exception type - Port not found.

Then I tried to determine, what com ports do I have:

```<code> String[] portNames = SerialPortList.getPortNames();
    for (int i = 0; i < portNames.length; i++) {
        System.out.println(portNames[i]);
    }
</code>```

The result was deplorable: portNames was empty.

Would you please advice me something.

答:
There are various ways to handle this.

When application is started, loop over to find what COM Ports are available than open the port only when it has been found. You can also add delay as Windows takes some time to detect and activate the COM Port for use. Windows loads driver and assign a COM port number when we plugin the USB-UART. This means if we insert same module to same physical port every time you will get COM4. So no worries.

If you want to make some more robust solution than, either write your own and use some library that provide USB-UART hotplug detection. So when we insert USB-UART module, this library will tell us which port number is assigned and we open it from our application. One such library I know is SerialPundit

Title: Com ports are not detected with jSSC

Body:
I'm trying to implement the transfering data with the help of Com ports in my java application. Firstly I decided to create SerialPort object like this.

 SerialPort serialPort = new SerialPort("COM1");

 try {
        serialPort.openPort();
 } catch (SerialPortException ex) {
        ex.printStackTrace();
 }

However there was an jssc.SerialPortException: Port name - COM1; Method name - openPort(); Exception type - Port not found.

Then I tried to determine, what com ports do I have:

 String[] portNames = SerialPortList.getPortNames();
    for (int i = 0; i < portNames.length; i++) {
        System.out.println(portNames[i]);
    }

The result was deplorable: portNames was empty.

Would you please advice me something.


问:
WebClient DownloadFile not working when download docx file with canvas from VSTS
When I download .docx file that contains 'Drawing Canvas' from VSTS with WebClient then downloaded .docx document is broken.
When I said broken, I mean that we cannot manually open Word document and we have next error message:” The file is corrupt and cannot be opened”.

This is only happening if word file contains canvas and if is downloaded from VSTS ?!
If I download from TFS2017 or if .docx file does not contains Canvas than everything is working.

Firstly, I was thinking that issue is related to Encoding, so I tested all encodings that I’ve found inside of WebClient.
Making any change related to Encoding didn’t resolve current issue.

Also, I’ve tried to change implementation in a way that we don’t use method DownloadFile and instead of that, I downloaded array of bytes and based on bytes generated Word document.
With that change in implementation, we’ve the same issue as before.

This is code example:

```<code> static void Main(string[] args)
        {
            var tfsUri = new Uri("https://.../");
            var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsUri);
            var workItemStore = projectCollection.GetService<WorkItemStore>();
            var workItem = workItemStore.GetWorkItem(2);
            projectCollection.EnsureAuthenticated();
            var credentials = workItemStore.TeamProjectCollection.Credentials;
            var fileName = "D:\\test_folder\\files\\System.Description.docx";
            var uri = workItem.Attachments[0].Uri;
            using (var request = new WebClient() { Credentials = credentials })
            {
                request.DownloadFile(uri, fileName);
            }
        }
</code>```

Thank you for your help if you have any idea.

答:
This issue was not caused by the canvas in the docx file. The file should be corrupted even there is only text in your docx file if you download it from VSTS with your code.

The issue here is that the authentication to VSTS is different with TFS, so the WebClient download file request is actually getting 401 when download the file since it don't have required permission to download the file. Update your code to following and then try again:

```<code>    using System;
    using Microsoft.TeamFoundation.Client;
    using Microsoft.TeamFoundation.WorkItemTracking.Client;
    using Microsoft.TeamFoundation.WorkItemTracking.Proxy;
    using System.IO;

    namespace GetAdmin
    {
        class Program
        {
            static void Main(string[] args)
            {

                TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri("https://xxx.visualstudio.com/"));
                ttpc.EnsureAuthenticated();
                WorkItemStore wistore = ttpc.GetService<WorkItemStore>();
                WorkItem wi = wistore.GetWorkItem(111);
                WorkItemServer wiserver = ttpc.GetService<WorkItemServer>();
                string tmppath = wiserver.DownloadFile(wi.Attachments[0].Id);
                string filename = @"D:\test\test.docx";
                File.Copy(tmppath,filename);
            }
        }

}
</code>```

Body:
When I download .docx file that contains 'Drawing Canvas' from VSTS with WebClient then downloaded .docx document is broken.
When I said broken, I mean that we cannot manually open Word document and we have next error message:” The file is corrupt and cannot be opened”.

This is only happening if word file contains canvas and if is downloaded from VSTS ?!
If I download from TFS2017 or if .docx file does not contains Canvas than everything is working.

Firstly, I was thinking that issue is related to Encoding, so I tested all encodings that I’ve found inside of WebClient.
Making any change related to Encoding didn’t resolve current issue.

Also, I’ve tried to change implementation in a way that we don’t use method DownloadFile and instead of that, I downloaded array of bytes and based on bytes generated Word document.
With that change in implementation, we’ve the same issue as before.

This is code example:

 static void Main(string[] args)
        {
            var tfsUri = new Uri("https://.../");
            var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsUri);
            var workItemStore = projectCollection.GetService<WorkItemStore>();
            var workItem = workItemStore.GetWorkItem(2);
            projectCollection.EnsureAuthenticated();
            var credentials = workItemStore.TeamProjectCollection.Credentials;
            var fileName = "D:\\test_folder\\files\\System.Description.docx";
            var uri = workItem.Attachments[0].Uri;
            using (var request = new WebClient() { Credentials = credentials })
            {
                request.DownloadFile(uri, fileName);
            }
        }

Thank you for your help if you have any idea.

Body:
This issue was not caused by the canvas in the docx file. The file should be corrupted even there is only text in your docx file if you download it from VSTS with your code.

The issue here is that the authentication to VSTS is different with TFS, so the WebClient download file request is actually getting 401 when download the file since it don't have required permission to download the file. Update your code to following and then try again:

    using System;
    using Microsoft.TeamFoundation.Client;
    using Microsoft.TeamFoundation.WorkItemTracking.Client;
    using Microsoft.TeamFoundation.WorkItemTracking.Proxy;
    using System.IO;

    namespace GetAdmin
    {
        class Program
        {
            static void Main(string[] args)
            {

                TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri("https://xxx.visualstudio.com/"));
                ttpc.EnsureAuthenticated();
                WorkItemStore wistore = ttpc.GetService<WorkItemStore>();
                WorkItem wi = wistore.GetWorkItem(111);
                WorkItemServer wiserver = ttpc.GetService<WorkItemServer>();
                string tmppath = wiserver.DownloadFile(wi.Attachments[0].Id);
                string filename = @"D:\test\test.docx";
                File.Copy(tmppath,filename);
            }
        }

}


问:
unable to hide .php extension. It worked only if i typed manually in url, How to fix it with .htaccess
My problem is that when I type the URL without .php extension (like as https://example.com/register) it worked, but when I click register link it redirect to https://example.com/register.php. I am trying to edit .htaccess file so that by default when I click register link URL should be without .php extension.

My go daddy .htaccess file code is

```<code>Options +MultiViews
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
</code>```

答:
Thanks to all for contribution, and being ashamed myself not to reply your valuable efforts because my boss was asign me a different project.

working code is

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
</code>```

Additionally also remove .php extention from
Example all anchor tag of the page.
you can check here https://doxdocs.com/

Body:
My problem is that when I type the URL without .php extension (like as https://example.com/register) it worked, but when I click register link it redirect to https://example.com/register.php. I am trying to edit .htaccess file so that by default when I click register link URL should be without .php extension.

My go daddy .htaccess file code is

Options +MultiViews
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Body:
Thanks to all for contribution, and being ashamed myself not to reply your valuable efforts because my boss was asign me a different project.

working code is

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Additionally also remove .php extention from
<a href="example.php">Example</a> all anchor tag of the page.
you can check here https://doxdocs.com/


问:
Node js Couch base connection error
Below is the set of nodejs code am using for connecting to couchbase.
Code::

```<code>`var couchbase = require('couchbase');
var appConfig = require('./app');
var cluster = new couchbase.Cluster(appConfig.database.couchbase.userBrand.host + ":" + appConfig.database.couchbase.userBrand.port);
//cluster.authenticate( 'username', 'password');
var bucket  = cluster.openBucket(appConfig.database.couchbase.userBrand.bucketName);
bucket.operationTimeout = 70 * 1000;
bucket.on('error', function(err) {
  console.log('CONNECT ERROR:', err);
});
exports.userBrand = bucket;`
</code>```

But am getting the below error::

```<code>**CONNECT ERROR: { [Error: failed to connect to bucket] code: 2 }**
</code>```

Am very new to nodejs as well as Couchbase.
Please excuse my language.
Thanks

答: You have authentication commented out, this is why it cannot connect. You have to provide username/password to connect the Couchbase Server. Find more information in the official documentation: https://developer.couchbase.com/documentation/server/current/sdk/nodejs/sdk-authentication-overview.html</p>

Title: Node js Couch base connection error

Body:
Below is the set of nodejs code am using for connecting to couchbase.
Code::

`var couchbase = require('couchbase');
var appConfig = require('./app');
var cluster = new couchbase.Cluster(appConfig.database.couchbase.userBrand.host + ":" + appConfig.database.couchbase.userBrand.port);
//cluster.authenticate( 'username', 'password');
var bucket  = cluster.openBucket(appConfig.database.couchbase.userBrand.bucketName);
bucket.operationTimeout = 70 * 1000;
bucket.on('error', function(err) {
  console.log('CONNECT ERROR:', err);
});
exports.userBrand = bucket;`

But am getting the below error::

**CONNECT ERROR: { [Error: failed to connect to bucket] code: 2 }**

Am very new to nodejs as well as Couchbase.
Please excuse my language.
Thanks


问:
How to send and get data in unet
I'm new to unity and unet. I'm trying to make a cricket game.
I want to share a boolean variable between two clients.

```<code>if(isBatting==null){

    if (random.Next (0, 2) == 1) {

        isBatting = true;
        Instantiate(batsmanPrefab, batsmanPrefab.transform.position, batsmanPrefab.transform.rotation);

    }else {

        isBatting = false;
        Instantiate(bowlerPrefab, bowlerPrefab.transform.position, bowlerPrefab.transform.rotation);

    }

}else{

    if(isBatting){

        Instantiate(bowlerPrefab, bowlerPrefab.transform.position, bowlerPrefab.transform.rotation);

    }else{

        Instantiate(batsmanPrefab, batsmanPrefab.transform.position, batsmanPrefab.transform.rotation);

    }

}
</code>```

in the above code, when the first person joins the network, the code will randomly assign it to batting and bowling mode. Then when another joins, he will get the current state from that boolean and get its opposite mode. But i am completely beginner in unity. So i have no idea, how to send and get data from the network server.

need help...

答:
One of the way, by using Command and RPC special methods.

Command Function runs on server : You first send your desired data
on server

Then, Use RPC function to send data to connected client (inform
connected clients).

As you are newbie I will recommend you to learn UNET first.
Here, are some useful links

UNet Concepts

GTGD Tut

Unet Actions

Netwrok Manager

give sometime in learnig follow at least on tut and docs.

Title: How to send and get data in unet

Body:
I'm new to unity and unet. I'm trying to make a cricket game.
I want to share a boolean variable between two clients.

if(isBatting==null){

    if (random.Next (0, 2) == 1) {

        isBatting = true;
        Instantiate(batsmanPrefab, batsmanPrefab.transform.position, batsmanPrefab.transform.rotation);

    }else {

        isBatting = false;
        Instantiate(bowlerPrefab, bowlerPrefab.transform.position, bowlerPrefab.transform.rotation);

    }

}else{

    if(isBatting){

        Instantiate(bowlerPrefab, bowlerPrefab.transform.position, bowlerPrefab.transform.rotation);

    }else{

        Instantiate(batsmanPrefab, batsmanPrefab.transform.position, batsmanPrefab.transform.rotation);

    }

}

in the above code, when the first person joins the network, the code will randomly assign it to batting and bowling mode. Then when another joins, he will get the current state from that boolean and get its opposite mode. But i am completely beginner in unity. So i have no idea, how to send and get data from the network server.

need help...

ContentLicense: CC BY-SA 4.0


答:
Do like this

Declare
private Activity activity;

on top. Then write below function

```<code>@Override
public void onAttach(Context context)
{
    super.onAttach(context);
    if (context instanceof Activity)
    {
        activity = (Activity) context;
    }
}
</code>```

Then use like this

```<code>if (isVisibleToUser) {
    (activity).getSupportActionBar().setDisplayHomeAsUpEnabled(false); //Null pointer exception thrown here
    (activity).setToolBarTitle(FragTitle);

}
</code>```

Title: getActivity returning Null Pointer Exception when called from Fragment setUserVisibleHint

Body:
Do like this

Declare
private Activity activity;

on top. Then write below function

@Override
public void onAttach(Context context)
{
    super.onAttach(context);
    if (context instanceof Activity)
    {
        activity = (Activity) context;
    }
}

Then use like this

if (isVisibleToUser) {
    (activity).getSupportActionBar().setDisplayHomeAsUpEnabled(false); //Null pointer exception thrown here
    (activity).setToolBarTitle(FragTitle);

}


问:
Node js App stoping When Console is closed
Am new to node , created my first express based app and deployed in my development server.

```<code>node app.js
</code>```

given above command no errors and working properly , after logoff my putty application seems to be stopped ,how can i solve this issue .

Is there any other way for running node apps.

答:
Install forever  using npm install forever -g

then use this command

```<code>forever start app.js
</code>```

https://www.npmjs.com/package/forever

Body:
Am new to node , created my first express based app and deployed in my development server.

node app.js

given above command no errors and working properly , after logoff my putty application seems to be stopped ,how can i solve this issue .

Is there any other way for running node apps.

Body:
Install forever  using npm install forever -g

then use this command

forever start app.js

https://www.npmjs.com/package/forever