我正在创建一个Android应用程序,我在其中显示项目列表,用户可以从中进行选择。我试图更新列表,如果项目,但应用程序一直崩溃,无论我写什么代码。以下是我正在做的事情
在OnCreate方法中,我有以下代码
adapter = new ArrayAdapter<String>(getActivity(), layout, showArray);
setListAdapter(adapter);
目前,showArray是一个空数组,现在appciation工作。
接下来,我在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";
}
}
谁能告诉我我做错了什么?
提前谢谢 感谢所有回复克莱夫
答案 0 :(得分:1)
如果您想更新列表,只需输入此代码。它将更新listview更新数据的适配器。
adapter.notifyDataSetChanged();
答案 1 :(得分:1)
我很确定问题是你不止一次打电话给setListAdapter
。您应该只在构建ListFragment时调用它。如果要修改列表,则必须通过调用适配器的add()
和remove()
方法将数据添加到基础数据结构中。
即:
adapter.add(object);
adapter.notifyDataSetChanged()
通常我会创建一个包装器方法来向适配器添加数据。