Bati Bati - 5 months ago 10
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:
MainActivity.java, its layout, activity_main.xml (Its for already built in navigation bar).
MainFragment.java, 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 MainActivity.java instead of MainFragment.java.

Here is the code.

Every answer will be appreciated.

Answer

Your buttons are in fragment_main.xml which is used in MainFragment.java but you are using those buttons in MainActivity.java, 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 MainFragment.java like this

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    Button b2 = (Button) view.findViewById(R.id.encb);
    b2.setOnClickListener(new View.OnClickListener() {
        @Override
        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

Comments