更改ArrayAdapter的更改内容不会更新

时间:2014-02-06 09:38:36

标签: android android-arrayadapter android-adapter

清除或添加数据不会在我的自定义ArrayAdapter类的方法addData中更新。到底是怎么回事?我也尝试更新List,它被送入ArrayAdapter并且也不会被更改,两次适配器中的项目数保持不变。请帮忙!

类别:

package sukh.app.ireddit;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

/**
 * While this looks like a lot of code, all this class
 * actually does is load the posts in to the listview.
 * 
 * @author Hathy 
 */
public class PostsFragment extends Fragment{

    ListView postsList;
    PostAdapter adapter;
    Handler handler;
    Activity activity;

    String subreddit;
    List<Post> posts;
    PostsHolder postsHolder;

    public PostsFragment(){
        handler=new Handler();
        posts=new ArrayList<Post>();
        activity=getActivity();
    }    

    public static Fragment newInstance(String subreddit){
        PostsFragment pf=new PostsFragment();
        pf.subreddit=subreddit;
        pf.postsHolder=new PostsHolder(pf.subreddit);        
        return pf;
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.posts
                                , container
                                , false);
        postsList=(ListView)v.findViewById(R.id.posts_list);
        return v;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {    
        super.onActivityCreated(savedInstanceState);
        initialize();
    }

    private void initialize(){
        // This should run only once for the fragment as the
        // setRetainInstance(true) method has been called on
        // this fragment

        if(posts.size()==0){

            // Must execute network tasks outside the UI
            // thread. So create a new thread.

            new Thread(){
                public void run(){
                    posts.addAll(postsHolder.fetchPosts());

                    // UI elements should be accessed only in
                    // the primary thread, so we must use the
                    // handler here.

                    handler.post(new Runnable(){
                        public void run(){
                            createAdapter();
                        }
                    });
                }
            }.start();
        }else{
            createAdapter();
        }
    }
   /**
     * This method creates the adapter from the list of posts
     * , and assigns it to the list.
     */
    private void createAdapter(){

        // Make sure this fragment is still a part of the activity.
        if(getActivity()==null) return;

        adapter=new PostAdapter(posts);
        postsList.setAdapter(adapter);
        Log.i("sukh", "setting adapter");
        postsList.setOnScrollListener(adapter);
    }

    protected class PostAdapter extends ArrayAdapter<Post> implements OnScrollListener {
        private int previousTotal = 0;
        private boolean loading = true;
        //PostAdapter _adapter = this;

        public PostAdapter(List<Post> posts){
            super(getActivity(), R.layout.post_item, posts);
        }   

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView == null){
                convertView = getActivity().getLayoutInflater().inflate(R.layout.post_item, null);
            }

            Post thePost = getItem(position);

            TextView postTitleTextView = (TextView) convertView.findViewById(R.id.post_title);
            postTitleTextView.setText(thePost.getTitle());

            TextView postDetailsTextView = (TextView) convertView.findViewById(R.id.post_details);
            postDetailsTextView.setText(thePost.getDetails());

            TextView postScoreTextView = (TextView) convertView.findViewById(R.id.post_score);
            postScoreTextView.setText(thePost.getScore());

            return convertView;
        }

        private void addData() {
            //final List<Post> newPosts = new ArrayList<Post>();
            Log.i("update1", this.adapterToString());
            new Thread(){
                public void run(){
                    //neither of these following statements make a difference
                    //neither does posts.clear() or posts.addAll...
                    //adapter.addAll(postsHolder.fetchMorePosts());
                    adapter.clear();
                }
            };
            Log.i("sukh", "executed scroll");       
        adapter.notifyDataSetChanged();
        Log.i("update2", this.adapterToString());
        }

        private String adapterToString() {
            StringBuilder sb = new StringBuilder();
            int total = this.getCount();
            sb.append("contents: ");
            /*for (int i = 0; i < this.getCount(); i ++) {
                sb.append(this.getItem(i).title + "/n");
            }*/
            //return sb.toString();
            return sb.append(total).toString();
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            if (loading) {
                if (totalItemCount > previousTotal) {
                    loading = false;
                    previousTotal = totalItemCount;     
                }
            }

            if (!loading && 
                    (firstVisibleItem + visibleItemCount + 1 >= totalItemCount)
                    ) {
                addData();
                loading = true;
            }

        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }
    }


}

编辑:已修复。添加了扩展ASyncTask的新类,并在更新适配器之前将其设置为fetchMorePosts。

显示了类:

private class AddPostsTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            Log.i("update2", "start fetchMorePosts");
            posts.addAll(postsHolder.fetchMorePosts());
            Log.i("update2", "end fetchMorePosts");
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            Log.i("update2", "start adapterChange");
            adapter.notifyDataSetChanged();
            Log.i("update2", "start adapterChange");
            super.onPostExecute(result);
        }

    }

1 个答案:

答案 0 :(得分:0)

在你的addData函数中,你在调用notifyDataSetChanged()之后在一个线程中清除适配器。