javaandroid

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference


I always get an Error in my Android Project.

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference

In my MainActivity i am calling the class FragmentStart.

FragmentStart.class

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class FragmentStart extends Fragment {

    //Define Listview
    private ListView startList;
    private String[] stringList;
    Activity activity = getActivity();

    public FragmentStart() {
        //
    }


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

        // Create ListView start
        startList = (ListView) rootView.findViewById(R.id.startList);
        stringList = getResources().getStringArray(R.array.startList);

        if (activity != null) {
            ArrayAdapter<String> objAdapter = new ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, stringList);
            startList.setAdapter(objAdapter);
            startList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switch (startList.getPositionForView(view)) {

                        case 0:
                            // ...
                            break;

                    }
                }
            });
        }
        // Create ListView end

        //New Entry
        Button add = (Button) activity.findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), addItem.class);
                startActivityForResult(myIntent, 0);
            }

        });

        return rootView;
    }
}


Solution

  • In addition to what @Selvin pointed out, it looks like this:

    Button add = (Button) activity.findViewById(R.id.add);
    

    ...should be changed to this:

    Button add = (Button) rootView.findViewById(R.id.add);