creating an empty ArrayList in android
<p>I'm trying to use an ArrayList to store an array of objects and then pass them to my adapter. </p>

<pre><code>public ArrayList&lt;Song&gt; arrayOfSongs;
public SongsAdapter adapter;
</code></pre>

<p>I initially just declare my <code>arrayofSongs</code>. Then I initialize inside <code>onCreateView()</code> in my fragment </p>

<pre><code>arrayOfSongs = new ArrayList&lt;&gt;();
adapter = new SongsAdapter(getContext(), arrayOfSongs);
</code></pre>

<p>The problem is that variable is initally null, and that gave me a lot of problems when I tried to use the adapter to populate the views initially. So I had to override my adapter's <code>getView</code> to return 0 if the array was null <a href="https://stackoverflow.com/questions/36157482/creating-an-adapter-for-listview-without-passing-an-array-initially">as suggested</a>. Some comments told me that it was better just to "initialize an empty ArrayList to put into the adapter instead of using a null check inside of the adapter". How would I do this because I'm getting a null pointer exception when I call <code>adapter.clear()</code></p>

<p>here is my SearchFragment</p>

<p>public class SearchFragment extends Fragment {</p>

<pre><code>// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

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

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment SearchFragment.
 */
// TODO: Rename and change types and number of parameters
public static SearchFragment newInstance(String param1, String param2) {
    SearchFragment fragment = new SearchFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

public EditText editText;
public ImageButton searchButton;
public ProgressBar pb;
public ListView lv;
public ArrayList&lt;Song&gt; arrayOfSongs;
public SongsAdapter adapter;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

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

    arrayOfSongs = new ArrayList&lt;&gt;();
    adapter = new SongsAdapter(getContext(), arrayOfSongs);

    editText = (EditText) rootView.findViewById(R.id.edit_message);
    searchButton = (ImageButton) rootView.findViewById(R.id.search_button);
    lv = (ListView) rootView.findViewById(R.id.listView);
    lv.setAdapter(adapter);
    pb = (ProgressBar) rootView.findViewById(R.id.progressBar);
    pb.setIndeterminate(true);
    pb.setVisibility(ProgressBar.INVISIBLE);

    searchButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String searchWords = editText.getText().toString();
            if (!searchWords.matches(""))
                hitItunes(searchWords);
        }
    });

    editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String searchWords = editText.getText().toString();
                if (!searchWords.matches("")) {
                    hitItunes(searchWords);
                    handled = true;
                }
            }
            return handled;
        }
    });

    return rootView;
}

public void hitItunes(String searchWords) {
    pb.setVisibility(ProgressBar.VISIBLE);
    try {
        String url = "https://itunes.apple.com/search?term=" + URLEncoder.encode(searchWords, "UTF-8") + "&amp;country=US&amp;media=music&amp;limit=100";

        JsonObjectRequest req = new JsonObjectRequest(url, null,
                new Response.Listener&lt;JSONObject&gt;() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            VolleyLog.v("Response:%n %s", response.toString(4));
                            Log.d("volley_success", response.toString());
                            pb.setVisibility(ProgressBar.INVISIBLE);

                            JSONArray songsJSON = response.getJSONArray("results");
                            ArrayList&lt;Song&gt; songs = Song.fromJSON(songsJSON);
                            adapter.clear();
                            adapter.addAll(songs);
                            adapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.e("Error: ", error.getMessage());
                Log.d("volley_error", error.getMessage());
            }
        });

            /*
            RequestQueue reqQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
            reqQueue.add(req);
            */

        try {
            // add the request object to the queue to be executed
            ApplicationController.getInstance().addToRequestQueue(req);
        } catch (NullPointerException npe) {
            npe.printStackTrace();
        }
    } catch (UnsupportedEncodingException uee) {
        throw new AssertionError("UTF-8 is unknown");
    }
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
        /*
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
        */
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * &lt;p/&gt;
 * See the Android Training lesson &lt;a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * &gt;Communicating with Other Fragments&lt;/a&gt; for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}
</code></pre>

<p>}</p>

<p>and here is my logcat </p>

<pre><code>03-23 12:12:08.678 2574-2574/com.loomius.loomius E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com.loomius.loomius, PID: 2574
   java.lang.NullPointerException
       at android.widget.ArrayAdapter.clear(ArrayAdapter.java:258)
       at com.loomius.loomius.SearchFragment$3.onResponse(SearchFragment.java:159)
       at com.loomius.loomius.SearchFragment$3.onResponse(SearchFragment.java:148)
       at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
       at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
       at android.os.Handler.handleCallback(Handler.java:733)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:136)
       at android.app.ActivityThread.main(ActivityThread.java:5113)
       at java.lang.reflect.Method.invokeNative(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:515)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
       at dalvik.system.NativeStart.main(Native Method)
</code></pre>

<p>here is the SongsAdapter </p>

<pre><code>public class SongsAdapter extends ArrayAdapter&lt;Song&gt; {


    ArrayList&lt;Song&gt; mList;
    Context mContext;

    public SongsAdapter(Context context, ArrayList&lt;Song&gt; songs) {
        super(context, 0, songs);

        mList = songs;
        mContext = context;
    }


    @Override
    public int getCount() {
        if(mList==null) {
            return 0;
        }
        else {
            return mList.size();
        }
    }


    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Song song = getItem(position);

        if (convertView == null)
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_song, parent, false);

        TextView artistName = (TextView) convertView.findViewById(R.id.artistName);
        TextView trackName = (TextView) convertView.findViewById(R.id.trackName);

        artistName.setText(song.getArtist());
        trackName.setText(song.getTitle());

        return convertView;
    }
}
</code></pre>