【问题标题】:creating an empty ArrayList in android在android中创建一个空的ArrayList
【发布时间】:2016-03-23 17:43:14
【问题描述】:

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

public ArrayList<Song> arrayOfSongs;
public SongsAdapter adapter;

我最初只是声明我的arrayofSongs。然后我在我的片段中初始化 onCreateView()

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

问题是变量最初为空,当我最初尝试使用适配器填充视图时,这给了我很多问题。因此,如果数组为空as suggested,我必须覆盖我的适配器的getView 以返回 0。一些 cmets 告诉我,最好“初始化一个空的 ArrayList 以放入适配器,而不是在适配器内部使用空检查”。我该怎么做,因为当我调用 adapter.clear() 时出现空指针异常

这是我的 SearchFragment

公共类 SearchFragment 扩展片段 {

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

}

这是我的日志猫

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)

这里是 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;
    }
}

【问题讨论】:

  • arrayOfSongs 已初始化。初始化后使用它怎么可能为null?数组大小为 0
  • 请发布您的完整代码和 logcat
  • @thepoosh 好吧,我提出了 logcat
  • 你是只从发布的按钮还是从其他地方调用hitItunes
  • 如果没有SongsAdapter 的代码,就很难判断出了什么问题

标签: java android arraylist


【解决方案1】:

你可以解决这个问题

在调用adapter.clear() 之前检查它是否包含数据或不使用adapter.getCount()

if(adapter.getCount()>0)
   adapter.clear()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    相关资源
    最近更新 更多