notifyDataSetChanged时,适配器在asyncTask中无法正常工作?

时间:2016-09-06 13:49:42

标签: java android android-asynctask

我在尝试实现loadmore时遇到了问题,确切的问题是AsyncTask中的adapter.notifyDataSetChanged。我试图从这个时候实现https://github.com/shontauro/android-pulltorefresh-and-loadmore ,这个尝试尝试在Class中使用扩展ListActivity实现,但是我使用extend Fragment,无论如何这个代码正在工作,但是当尝试从loadmore获取数据时,数据没有更新。如果我的语言不好,我很抱歉:)

这是我的班级:

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.bye.swipetab.adapter.ViewPagerAdapter;
import com.viewpagerindicator.CirclePageIndicator;
import com.viewpagerindicator.UnderlinePageIndicator;

import java.util.Arrays;
import java.util.LinkedList;


public class Tour extends Fragment {
    private static final String TAG = Tour.class.getSimpleName();

    View myView;
    private String[] values ;
    private static final String brand_value = "brand_value";
    // Array of strings...
    String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry","WebOS"};

    // list with the data to show in the listview
    private LinkedList<String> mListItems;

    // The data to be displayed in the ListView
    private String[] mNames = { "Fabian", "Carlos", "Alex", "Andrea", "Karla",
            "Freddy", "Lazaro", "Hector", "Carolina", "Edwin", "Jhon",
            "Edelmira", "Andres" };


    // Declare Variables
    ViewPager viewPager;
    PagerAdapter vAdapter;
    String[] rank;
    String[] country;
    String[] population;
    int[] flag;
    UnderlinePageIndicator mIndicator;

    ListView listView;
    ArrayAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myView = inflater.inflate(R.layout.tour_layout, null);


        View header = inflater.inflate(R.layout.tour_header_layout, null);
        //View footer = inflater.inflate(R.layout.tour_footer_layout, null);

        listView = (ListView) myView.findViewById(android.R.id.list);
        listView.addHeaderView(header, null, false); // header will not be clickable

        mListItems = new LinkedList<String>();
        mListItems.addAll(Arrays.asList(mNames));
        adapter = new ArrayAdapter<String>(getActivity(), R.layout.tour_listview, R.id.MobileArray, mNames);

        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // When clicked, show a toast with the TextView text
                String brand_text = ((TextView) view.findViewById(R.id.MobileArray)).getText().toString();
                //Toast.makeText(getApplicationContext(),brand_text, Toast.LENGTH_SHORT).show();

                // Starting single contact activity
                Intent in = new Intent(getActivity(), TourActivity.class);
                in.putExtra(brand_value, brand_text);
                in.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(in);
            }
        });

        population = new String[] {
                        "1,354,040,000",
                        "1,210,193,422",
                        "315,761,000",
                        "315,123,000",
                        "363,752,000" };

        flag = new int[] {
                R.drawable.offline_ide_4,
                R.drawable.offline_ide_1,
                R.drawable.offline_ide_2,
                R.drawable.offline_ide_3,
                R.drawable.offline_ide_5 };

        // Locate the ViewPager in viewpager_main.xml
        viewPager = (ViewPager) myView.findViewById(R.id.pager);
        // Pass results to ViewPagerAdapter Class
        vAdapter = new ViewPagerAdapter(getContext(), rank, country, population, flag);
        // Binds the Adapter to the ViewPager
        viewPager.setAdapter(vAdapter);

        CirclePageIndicator indicator = (CirclePageIndicator)myView.findViewById(R.id.indicator);
        indicator.setViewPager(viewPager);

        final float density = getResources().getDisplayMetrics().density;
        indicator.setRadius(5 * density);
        //indicator.setBackgroundColor(0x7f0c006a);
        //indicator.setPageColor(R.color.black);
        //indicator.setFillColor(R.color.tab_bg_yellow_deep);
        //indicator.setStrokeColor(R.color.tab_bg_yellow_deep);
        //indicator.setStrokeWidth(2 * density);

        // set a listener to be invoked when the list reaches the end
        ((LoadMoreListView) listView)
                .setOnLoadMoreListener(new LoadMoreListView.OnLoadMoreListener() {
                    public void onLoadMore() {
                        // Do the work to load more items at the end of list
                        // here
                        new LoadDataTask().execute();
                    }
                });

        return myView;

    }

    private class LoadDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            if (isCancelled()) {
                return null;
            }

            // Simulates a background task
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }

            for (int i = 0; i < mobileArray.length; i++) {
                mListItems.add(mobileArray[i]);
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            mListItems.add("Added after load more");

            // We need notify the adapter that the data have been changed
            adapter.notifyDataSetChanged();

            // Call onLoadMoreComplete when the LoadMore task, has finished
            ((LoadMoreListView) listView).onLoadMoreComplete();

            super.onPostExecute(result);
        }

        @Override
        protected void onCancelled() {
            // Notify the loading more operation has finished
            ((LoadMoreListView) listView).onLoadMoreComplete();
        }
    }

}

请告诉我为什么这不起作用?

1 个答案:

答案 0 :(得分:0)

mListItems 不用于任何事情。

mNames 是链接到适配器的那个,而不是 mListItems ,您正在填写AsyncTask,可能您应该查看它。

mListItems.addAll(Arrays.asList(mNames));
adapter = new ArrayAdapter<String>(getActivity(), R.layout.tour_listview, R.id.MobileArray, mNames);

然后你做

        for (int i = 0; i < mobileArray.length; i++) {
            mListItems.add(mobileArray[i]);
        }