#android #listview #android-studio #arraylist #android-listfragment
#Android #listview #android-studio #arraylist #android-listfragment
Вопрос:
Кто-нибудь может мне помочь? Я хочу загружать больше данных при прокрутке вверх и вниз, используя AsyncTask.
я пытался использовать приведенный ниже код, но при прокрутке вниз загружается только более 10 данных, кроме того, он отображает те же данные. он не загружает новые данные.
Вот мой код:
MainActivity.java
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment, container, false);
arraylist1 = new ArrayList<>();
adapter = new ListViewAdapter(view.getContext(), R.layout.list_view_adapter, arraylist1);
listOfNews = (ListView) view.findViewById(R.id.listView);
//progress bar
dialog = new ProgressDialog(HotNewsFrag.this.getActivity());
dialog.setMessage("Loading News");
dialog.setCancelable(true);
//class to parse data from json
new ReadJSON().execute(url);
return view;
}
ListViewAdapter.java
public class ListViewAdapter extends ArrayAdapter<HotNews> {
private final LayoutInflater mInflater;
Context context;
ArrayList<HotNews> arrayList;
ImageView image;
TextView doer;
TextView date;
TextView text;
Days day = new Days();
public ListViewAdapter(Context context, int resource, ArrayList<HotNews> arrayList) {
super(context, resource, arrayList);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arrayList = arrayList;
this.context = context;
}
@Override
public int getCount() {
if (arrayList == null) {
return 0;
}
return arrayList.size();
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final HotNews news;
View v = convertView;
if (v == null) {
v = mInflater.inflate(R.layout.list_view_adapter, parent, false);
}
image = (ImageView) v.findViewById(R.id.imagetitle);
title = (TextView) v.findViewById(R.id.txtTitle);
doer = (TextView) v.findViewById(R.id.doer);
date = (TextView) v.findViewById(R.id.txtdate);
text = (TextView) v.findViewById(R.id.text);
news = getItem(position);
Picasso.with(getContext()).load(url news.getImage()).error(R.drawable.dap).noFade().into(image);
title.setText(news.getTitle());
doer.setText("ព័ត៍មានដោយ៖" news.getDoer());
date.setText(day.Days(news.getDate()) ":" news.getTime());
text.setText(news.getContent());
//set onItemListener
listOfNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(), "Stop Clicking me", Toast.LENGTH_SHORT).show();
Intent detail = new Intent(getContext(), HotNewsDetail.class);
detail.putExtra(newsid, String.valueOf(getItem(position).getId()));
startActivity(detail);
}
});
listOfNews.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == 0) {
// new loadMoreListView().execute();
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
final int lastItem = firstVisibleItem visibleItemCount;
if (lastItem == totalItemCount) {
new ReadJSON().execute(url);
} else {
}
}
});
return v;
}
}
ReadJSON AsyncTask
private class ReadJSON extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... url) {
String st = readURL(url[0]);
Log.d("st", st);
return st;
}
@Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.optJSONArray("data");
for (int i = 0; i < jsonArray.length(); i ) {
Log.d(i ":jsonArray object", jsonArray.toString() " size= " jsonArray.length());
JSONObject productObject = jsonArray.optJSONObject(i);
JSONObject img = productObject.optJSONObject("image");
if (img != null) {
JSONObject da = img.optJSONObject("data");
if (da != null) {
arraylist1.add(new HotNews(
da.optString("filename"),
productObject.optString("title"),
productObject.optString("article_by"),
productObject.optString("date_publish"),
productObject.optString("short_description"),
productObject.optInt("id"),
productObject.optString("time_publish")
));
Log.d("jsonArray news list1", arraylist1.size() "");
}
} else {
arraylist1.add(new HotNews(
"",
productObject.optString("title"),
productObject.optString("article_by"),
productObject.optString("date_publish"),
productObject.optString("short_description"),
productObject.optInt("id"),
productObject.optString("time_publish")
));
}
}
listOfNews.setAdapter(adapter);
adapter.notifyDataSetChanged();
dialog.dismiss();
// super.onPostExecute(content);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected void onPreExecute() {
dialog.show();
super.onPreExecute();
}
}
Ответ №1:
Пожалуйста, обновите номер страницы или обновите URL-адрес при каждом вызове, если вы хотите получать новые данные при прокрутке, и удалите метод listOfNews.setAdapter(adapter);
from onPostExecute()
в ReadJSON
классе и установите для него значение listview в onCreate()
методе после
listOfNews = (ListView) view.findViewById(R.id.listView);