gpt4 book ai didi

java - 在android中创建一个空的ArrayList

转载 作者:行者123 更新时间:2023-12-02 03:47:32 27 4
gpt4 key购买 nike

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

public ArrayList<Song> arrayOfSongs;
public SongsAdapter adapter;

我最初只是声明我的arrayofSongs。然后我在 fragment 的 onCreateView() 内部进行初始化

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

问题是变量最初为空,当我最初尝试使用适配器填充 View 时,这给我带来了很多问题。因此,如果数组为空,我必须重写适配器的 getView 以返回 0 as suggested 。一些评论告诉我,最好“初始化一个空的 ArrayList 以放入适配器中,而不是在适配器内部使用空检查”。我该如何执行此操作,因为当我调用 adapter.clear()

时出现空指针异常

这是我的搜索 fragment

公共(public)类 SearchFragment 扩展 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);
}

}

这是我的 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)

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

最佳答案

你可以通过以下方式解决这个问题

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

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

关于java - 在android中创建一个空的ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36171311/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com