我正在尝试制作一个listView
,当最后一个listView
项目可见时,它会加载更多项目。我有从JSON获取数据的代码,该代码运行良好。
这是我的 MyFragment.java
public class MyFragment extends Fragment {
JSONObject jsonobject;
JSONObject newjsonobject;
JSONArray jsonarray;
JSONArray newjsonarray;
ListView listview;
ListViewAdapter adapter;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<HashMap<String, String>> newarraylist;
public static String NAME = "name";
private int preLast;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.listview_main, container, false);
new DownloadJSON().execute();
return rootView;
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
arraylist = new ArrayList<HashMap<String, String>>();
jsonobject = JSONfunctions.getJSONfromURL("http://192.168.0.103/contacts.json");
try {
jsonarray = jsonobject.getJSONArray("contacts");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
map.put("name", jsonobject.getString("name"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void args) {
listview = (ListView) getActivity().findViewById(R.id.listview);
adapter = new ListViewAdapter(getActivity(), arraylist);
listview.setOnScrollListener(new AbsListView.OnScrollListener(){
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
final int lastItem = firstVisibleItem + visibleItemCount;
newarraylist = new ArrayList<HashMap<String, String>>();
if(lastItem == totalItemCount) {
if(preLast!=lastItem){
preLast = lastItem;
newjsonobject = JSONfunctions.getJSONfromURL("http://192.168.0.103/contacts2.json");
try {
newjsonarray = newjsonobject.getJSONArray("contacts");
for (int i = 0; i < newjsonarray.length(); i++) {
HashMap<String, String> newmap = new HashMap<String, String>();
newjsonobject = newjsonarray.getJSONObject(i);
newmap.put("name", newjsonobject.getString("name"));
newarraylist.add(newmap);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
arraylist.addAll(newarraylist);
adapter.notifyDataSetChanged();
}
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState){}
});
listview.setAdapter(adapter);
}
}
}
如果我尝试这样做,那就好了
newmap.put("name", "Name");
newarraylist.add(newmap);
arraylist.addAll(newarraylist);
adapter.notifyDataSetChanged();
但是当我尝试从JSON获取数据时,当我滚动到最后一个项目时,应用程序停止工作。我做错了什么?
Contacts2.json
{
"contacts": [
{
"name": "Name"
},
{
"name": "Name 2"
}
]
}