我正在创建一个 android 应用程序,在其中显示项目列表,用户可以从中进行选择。我正在尝试更新列表,如果项目但应用程序一直在崩溃,无论我写什么代码。以下是我在做什么
在 OnCreate 方法中,我有以下代码
adapter = new ArrayAdapter<String>(getActivity(), layout, showArray);
setListAdapter(adapter);
目前, showArray 是一个空数组,目前该应用程序有效。
接下来,我在 showArray 中插入数据,并尝试用另一种方法更新列表适配器。我正在使用以下代码:
adapter = new ArrayAdapter<String>(getActivity(), layout, showArray);
setListAdapter(adapter);
但应用程序崩溃。我试图将我的代码更改为:
adapter = new ArrayAdapter<String>(getActivity(), layout, showArray);
adapter.notifyDataSetChanged();
但再次没有运气。
我的完整代码如下:
public class Fragment_AllCommunities extends Fragment {
OnHeadlineSelectedListener callBack;
// The container Activity must implement this interface so the frag can deliver messages
public interface OnHeadlineSelectedListener {
public void onCommunitySelected(int position);
}
private ProgressDialog progress;
private Activity activity;
private JSONArray communities;
private JSONObject[] commDetails;
private String[] showArray = {""};
private int layout = 0;
private ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We need to use a different list item layout for devices older than Honeycomb
layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;
adapter = new ArrayAdapter<String>(getActivity(), layout, showArray);
setListAdapter(adapter);
}
public void updateAllCommunities(JSONObject[] commArr) throws JSONException {
commDetails = commArr;
showArray = new String[commDetails.length];
for(int i=0;i<commDetails.length;i++)
{
showArray[i] = commDetails[i].getString("name").toString();
}
//adapter = new ArrayAdapter<String>(getActivity(), layout, showArray);
//adapter.notifyDataSetChanged();
try
{
adapter.notifyDataSetChanged();
}
catch(Exception ex)
{
String s = ex.getMessage();
}
}
@Override
public void onStart() {
super.onStart();
if (getFragmentManager().findFragmentById(R.id.view_community_fragment) != null) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//getListView().setItemChecked(0, true);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
callBack = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
callBack.onCommunitySelected(position);
getListView().setItemChecked(position, true);
}
@Override
public void onResume() {
super.onResume();
String a = "S";
}
}
谁能告诉我我做错了什么?
在此先感谢感谢所有回复
克莱夫