私はリストビューショーの名前、学校、リンクをURLから取得しています。各 URL には 30 個のアイテムがあり、リストビューのアイテムをさらにロードします。しかし、Asynctask を再呼び出しすると、新しいデータは追加されません。アプリを実行すると、NullpointerException が返されます。知っていれば...助けてください。皆さんありがとう。
すみません、英語が下手です!
ここに私のコード:
クラス InfoTeacherFragment
public class InfoTeacherFragment extends Fragment {
private String URL = "http://scv.udn.vn/dhdn/trdhsp/page/";
ProgressDialog pDialog;
Context mContext;
private ArrayList<ItemTeacher> data;
ItemTeacher itemTeacher = new ItemTeacher();
ListView lvItem;
DisplayImageOptions options;
ImageLoader imageloader;
View mFooterView;
InfoTeacher adapter;
ProgressBar loading;
int CurrentPage = 1;
int visibleThreshold = 3;
int startPage = 1;
boolean loadingMore = false;
public InfoTeacherFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_mission)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisk(true).considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565).build();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.teacherinfo_layout,
container, false);
mContext = container.getContext();
lvItem = (ListView) rootView.findViewById(R.id.lvTeacher);
data = new ArrayList<ItemTeacher>();
adapter = new InfoTeacher(mContext, data);
lvItem.setAdapter(adapter);
lvItem.setOnScrollListener(new EndlessScrollListener() {
@Override
public void onLoadMore(int page, int totalItemsCount) {
CurrentPage++;
customLoadMoreDataFromApi(CurrentPage);
}
});
imageloader = ImageLoader.getInstance();
imageloader.init(ImageLoaderConfiguration.createDefault(mContext));
if (Utils.isOnline(mContext) == true
&& Utils.KEY_CHECK_SUCCESS.equals("SUCCESS")) {
loadDataFromServer(URL + startPage);
} else if (Utils.isOnline(mContext) == true
&& Utils.KEY_CHECK_SUCCESS.equals("FAIL")) {
Utils.MyToast(Utils.KEYWORK_ERROR[0], R.drawable.warning_icon,
mContext, false);
}
isInitList = true;
lvItem.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter1, View view,
int position, long id) {
Intent intent = new Intent(mContext, NewsItemView.class);
if (!adapter.getItem(position).getLink().get(position)
.equalsIgnoreCase("")) {
Bundle bundle = new Bundle();
bundle.putSerializable(NewsItemView.ITEM_TEACHER,
adapter.getItemId(position));
bundle.putInt(NewsItemView.POSITION, position);
intent.putExtras(bundle);
startActivity(intent);
}
}
});
return rootView;
}
private void loadDataFromServer(String URL) {
LoadData loadData = new LoadData() {
@Override
protected void onPostExecute(ArrayList<ItemTeacher> result) {
super.onPostExecute(result);
updateListView(result);
}
};
loadData.execute(URL);
}
boolean isInitList = false;
protected void updateListView(ArrayList<ItemTeacher> result) {
if (!isInitList) {
data.addAll(result);
}
isInitList = false;
adapter.clear();
adapter.addAll(result);
adapter.notifyDataSetChanged();
}
@Override
public void onDestroy() {
super.onDestroy();
AnimateFirstDisplayListener.displayedImages.clear();
}
class LoadData extends AsyncTask<String, Void, ArrayList<ItemTeacher>> {
@Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(mContext, "", Utils.KEYWORK_ERROR[2]);
data = new ArrayList<ItemTeacher>();
super.onPreExecute();
}
@Override
protected ArrayList<ItemTeacher> doInBackground(String... params) {
data = Utils.getInformationTeacher(params[0]);
return data;
}
@Override
protected void onPostExecute(ArrayList<ItemTeacher> result) {
if (result != null) {
pDialog.dismiss();
} else if (result == null) {
pDialog.dismiss();
Utils.MyToast(Utils.KEYWORK_ERROR[0], R.drawable.warning_icon,
mContext, false);
}
super.onPostExecute(result);
}
}
class InfoTeacher extends ArrayAdapter<ItemTeacher> {
private LayoutInflater inflater;
ImageLoadingListener animateFirstListener;
List<ItemTeacher> item = new ArrayList<ItemTeacher>();
public InfoTeacher(Context context, List<ItemTeacher> objects) {
super(context, -1, objects);
this.item = objects;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
animateFirstListener = new AnimateFirstDisplayListener();
}
@Override
public View getView(int position, View convertView, ViewGroup arg2) {
itemTeacher = getItem(position);
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.teacher_layout, arg2,
false);
holder.Name = (TextView) convertView
.findViewById(R.id.tv_NameTeacher);
holder.School = (TextView) convertView
.findViewById(R.id.tv_School);
holder.ic_naviga = (ImageView) convertView
.findViewById(R.id.ivNaviga);
holder.icon = (ImageView) convertView
.findViewById(R.id.iv_IconTeacher);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.Name.setText(itemTeacher.getName().get(position));
holder.School.setText(itemTeacher.getSchool().get(position));
return convertView;
}
@Override
public int getCount() {
return item.size();
}
}
static class ViewHolder {
ImageView icon;
TextView Name;
TextView School;
ImageView ic_naviga;
}
private static class AnimateFirstDisplayListener extends
SimpleImageLoadingListener {
static final List<String> displayedImages = Collections
.synchronizedList(new LinkedList<String>());
@Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
public void customLoadMoreDataFromApi(int page) {
loadDataFromServer(URL + page);
}
}
アイテム先生
public class ItemTeacher {
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> icon = new ArrayList<String>();
private ArrayList<String> link = new ArrayList<String>();
private ArrayList<String> school = new ArrayList<String>();
public ItemTeacher(){
}
public ArrayList<String> getIcon() {
return icon;
}
public ArrayList<String> getLink() {
return link;
}
public ArrayList<String> getName() {
return name;
}
public ArrayList<String> getSchool() {
return school;
}
public void setIcon(ArrayList<String> icon) {
this.icon = icon;
}
public void setLink(ArrayList<String> link) {
this.link = link;
}
public void setName(ArrayList<String> name) {
this.name = name;
}
public void setSchool(ArrayList<String> school) {
this.school = school;
}
}
そして EndlessScrollListener
public abstract class EndlessScrollListener implements OnScrollListener {
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
// The current offset index of data you have loaded
private int currentPage = 0;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 0;
// True if we are still waiting for the last set of data to load.
private boolean loading = true;
// Sets the starting page index
private int startingPageIndex = 0;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
public EndlessScrollListener(int visibleThreshold, int startPage) {
this.visibleThreshold = visibleThreshold;
this.startingPageIndex = startPage;
this.currentPage = startPage;
}
// This happens many times a second during a scroll, so be wary of the code
// you place here.
// We are given a few useful parameters to help us work out if we need to
// load some more data,
// but first we check if we are waiting for the previous load to finish.
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state
if (totalItemCount < previousTotalItemCount) {
Log.i("abc", "ABC + totalItemCount < previousTotalItemCount");
this.currentPage = this.startingPageIndex;
this.previousTotalItemCount = totalItemCount;
if (totalItemCount == 0) {
this.loading = true;
}
}
// If it’s still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the
// current page
// number and total item count.
if (loading && (totalItemCount > previousTotalItemCount)) {
Log.i("abc", "ABC + totalItemCount > previousTotalItemCount");
loading = false;
previousTotalItemCount = totalItemCount;
currentPage++;
}
// If it isn’t currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to
// fetch the data.
if (!loading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
Log.i("abc", "ABC + !loading");
onLoadMore(currentPage + 1, totalItemCount);
loading = true;
}
}
// Defines the process for actually loading more data based on page
public abstract void onLoadMore(int page, int totalItemsCount);
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Don't take any action on changed
}
}
NullpointerException エラー
01-03 08:53:44.379: E/AndroidRuntime(5051): FATAL EXCEPTION: main
01-03 08:53:44.379: E/AndroidRuntime(5051): java.lang.IndexOutOfBoundsException: Invalid index 30, size is 30
01-03 08:53:44.379: E/AndroidRuntime(5051): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
01-03 08:53:44.379: E/AndroidRuntime(5051): at java.util.ArrayList.get(ArrayList.java:304)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.readnews.main.InfoTeacherFragment$InfoTeacher.getView(InfoTeacherFragment.java:215)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.widget.AbsListView.obtainView(AbsListView.java:2143)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.widget.ListView.makeAndAddView(ListView.java:1831)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.widget.ListView.fillDown(ListView.java:674)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.widget.ListView.fillGap(ListView.java:638)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4930)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:4087)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.view.Choreographer.doFrame(Choreographer.java:531)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.os.Handler.handleCallback(Handler.java:725)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.os.Handler.dispatchMessage(Handler.java:92)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.os.Looper.loop(Looper.java:137)
01-03 08:53:44.379: E/AndroidRuntime(5051): at android.app.ActivityThread.main(ActivityThread.java:5041)
01-03 08:53:44.379: E/AndroidRuntime(5051): at java.lang.reflect.Method.invokeNative(Native Method)
01-03 08:53:44.379: E/AndroidRuntime(5051): at java.lang.reflect.Method.invoke(Method.java:511)
01-03 08:53:44.379: E/AndroidRuntime(5051): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-03 08:53:44.379: E/AndroidRuntime(5051): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-03 08:53:44.379: E/AndroidRuntime(5051): at dalvik.system.NativeStart.main(Native Method)
更新 1:
関数はURLからデータを取得します
public static ArrayList<ItemTeacher> getInformationTeacher(String url) {
// Vector<ArrayList<String>> data = new Vector<ArrayList<String>>();
ArrayList<String> Name = new ArrayList<String>();
ArrayList<String> School = new ArrayList<String>();
ArrayList<String> Link = new ArrayList<String>();
// ArrayList<String> Icon = new ArrayList<String>();
ArrayList<ItemTeacher> itemTeachers = new ArrayList<ItemTeacher>();
ItemTeacher itemTeacher = new ItemTeacher();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
Document doc = Jsoup.connect(url).timeout(10 * 300).get();
Charset.forName("UTF-8");
doc.outputSettings().escapeMode(EscapeMode.xhtml);
Elements eles = doc.select("div#Thu tbody a.linkheader");
Elements elesIcon = doc.select("div#Thu img[src]");
int i = 0;
for (Element element : eles) {
i++;
String fillinfo = element.ownText();
String link = element.attr("href");
if (i % 2 == 0) {
School.add(fillinfo);
itemTeacher.setSchool(School);
} else {
Name.add(fillinfo);
itemTeacher.setName(Name);
Link.add(link);
itemTeacher.setLink(Link);
itemTeachers.add(itemTeacher);
}
}
for (Element icon : elesIcon) {
String hrefIcon = icon.attr("src");
}
} catch (IOException e) {
return null;
}
}
return itemTeachers;
}