在android中创建一个空的ArrayList

时间:2016-03-23 06:36:55

标签: java android arraylist

我正在尝试使用ArrayList来存储对象数组,然后将它们传递给我的适配器。

arrayofSongs

我最初只是宣布我的onCreateView()。然后我在我的片段

中的arrayOfSongs = new ArrayList<>(); adapter = new SongsAdapter(getContext(), arrayOfSongs); 内初始化
getView

问题是变量初始为null,当我尝试使用适配器最初填充视图时,这给了我很多问题。因此,如果数组为空as suggested,我必须覆盖我的适配器adapter.clear()以返回0。一些评论告诉我,最好只是“初始化一个空的ArrayList放入适配器,而不是在适配器内部使用空检查”。我该怎么做呢,因为当我调用// 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); }

时,我得到一个空指针异常

这是我的SearchFragment

public class SearchFragment扩展了Fragment {

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)

}

这是我的logcat

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;
    }
}

这里是SongsAdapter

{{1}}

1 个答案:

答案 0 :(得分:2)

您可以通过

解决此问题

在致电adapter.clear()之前,使用adapter.getCount()

检查它是否包含数据
if(adapter.getCount()>0)
   adapter.clear()