0

I'm trying to use an ArrayList to store an array of objects and then pass them to my adapter.

public ArrayList<Song> arrayOfSongs;
public SongsAdapter adapter;

I initially just declare my arrayofSongs. Then I initialize inside onCreateView() in my fragment

arrayOfSongs = new ArrayList<>();
adapter = new SongsAdapter(getContext(), arrayOfSongs);

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 getView to return 0 if the array was null as suggested. 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 adapter.clear()

here is my SearchFragment

public class SearchFragment extends Fragment {

// 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<Song> 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<>();
    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") + "&country=US&media=music&limit=100";

        JsonObjectRequest req = new JsonObjectRequest(url, null,
                new Response.Listener<JSONObject>() {
                    @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<Song> 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.
 * <p/>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}

and here is my logcat

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)

here is the SongsAdapter

public class SongsAdapter extends ArrayAdapter<Song> {


    ArrayList<Song> mList;
    Context mContext;

    public SongsAdapter(Context context, ArrayList<Song> 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;
    }
}
10
  • 2
    arrayOfSongs is initialized. How can it be null when you use it after initialization? array size is 0 Commented Mar 23, 2016 at 6:38
  • 1
    please post your full code and logcat Commented Mar 23, 2016 at 6:40
  • @thepoosh okay, I posed the logcat Commented Mar 23, 2016 at 6:43
  • 1
    Do you only call hitItunes from the posted button or from elsewhere, too? Commented Mar 23, 2016 at 6:46
  • Without the code for SongsAdapter it's hard to tell what's wrong Commented Mar 23, 2016 at 6:47

1 Answer 1

2

You can solve this by

before calling adapter.clear() check it contains data or not using adapter.getCount()

if(adapter.getCount()>0)
   adapter.clear()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.