Bati Bati - 1 year ago 73
Android Question

Application stopped error in android

I am a newbie.

I am getting "Application has stopped", error after pressing on Encrypt button (id=encb) (only name, for testing by Toast), in fragment_main.xml (Home).

Explanation:, its layout, activity_main.xml (Its for already built in navigation bar)., its layout, fragment_main.xml (Its for Home fragment in the navigation bar, from one of the fragments like Home, Settings etc.)

What I have tried: I have searched a lot for it on Internet. Checked my onClick function, it is correct.

Also as there is FragmentTransaction of the fragment_main (i.e.,
MainFragment), by activity_main. So, it means I have to put my onClick() in instead of

Here is the code.

Every answer will be appreciated.

Answer Source

Your buttons are in fragment_main.xml which is used in but you are using those buttons in, so it's coming out to be null which results in NullPointerException.

Solution 1: Use this if you want your buttons in the current fragment only.

Move button related code to like this

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    Button b2 = (Button) view.findViewById(;
    b2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            // click related code goes here
    return view;

Solution 2: Use this if you want your button to be there irrespective of the currently loaded fragment.

Add those buttons in activity_main.xml

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download