1

我使用PagerSlidingTabStrip库,但这个库有问题。我有一个 GridView,当页面更改时,它会通过 AsyncTask 从 Web 更新。if swipe from page 1 to page 2, page 2 get update from web but My problem is, when such as tab 1 is selected click on tab 2, page 2 not update and show page 1 content(grid adapter updated but pager not show new内容)。滑动更新内容,但选项卡选择不更新内容。我的代码有什么问题?

如何避免在寻呼机中缓存下一页和上一页?我想在选择任何页面时从服务器接收数据。

public class SubCategoryActivity extends SherlockFragmentActivity {

boolean firstPagerAdapterConfirmed = false;
LayoutInflater inflator;
PagerSlidingTabStrip tabs;
ViewPager pager;
MyPagerAdapter pagerAdapter;
TextView tvCustomTitle;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONArray jsonArray;


String[][] SubCat;
GridviewAdapter gridAdapter;
GridView gridViewSubCategory;
HashMap<String, String> map;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
Intent intent;
int recordNum = 0;
int totalItems = 0;
int pageNum = 1;
int itemsPerPage = 20;
boolean loadingMore = false;
int itemId[];
ProgressBar progressBar;
RelativeLayout relativeLayoutLoadingMore;

private class getSubCategoryObjects extends AsyncTask<String, Void, String> {

    int i = 0;

    @Override
    protected String doInBackground(String... url) {
        // TODO Auto-generated method stub
        return BaseActivity.jsonParser.makeHttpRequest(url[0], "POST",
                nameValuePairs);
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
        // progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        try {
            jsonArray = new JSONArray(result);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (pageNum == 1 ) {
            i = 3;
            try {
                recordNum = jsonArray.getJSONObject(0).getInt("recordNum");
                totalItems = jsonArray.getJSONObject(1)
                        .getInt("totalItems");

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            itemId = new int[totalItems];
            for (int i = 0; i < totalItems; i++) {

                try {
                    itemId[i] = jsonArray.getJSONObject(2).getInt(
                            String.valueOf(i));
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        for (; i < jsonArray.length(); i++) {
            JSONObject jsonObjet;
            map = new HashMap<String, String>();
            try {

                jsonObjet = jsonArray.getJSONObject(i);
                map.put("id", String.valueOf(jsonObjet.getInt("id")));
                map.put("title", jsonObjet.getString("title_fa"));
                map.put("image", jsonObjet.getString("image"));
                map.put("price", jsonObjet.getString("price"));
                map.put("date", jsonObjet.getString("date"));

                list.add(map);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }

        }

        if (pageNum == 1 && firstPagerAdapterConfirmed == false) {
        //  progressBar.setVisibility(View.GONE);
            gridAdapter = new GridviewAdapter(SubCategoryActivity.this,
                    list);
            pagerAdapter = new MyPagerAdapter(gridAdapter);

            pager.setAdapter(pagerAdapter);
            firstPagerAdapterConfirmed = true;
            //pager.setOffscreenPageLimit(1);

        }else if(pageNum == 1 && firstPagerAdapterConfirmed) {
            //progressBar.setVisibility(View.GONE);
            gridAdapter = new GridviewAdapter(SubCategoryActivity.this,
                    list);
            gridViewSubCategory.setAdapter(gridAdapter);

        }else {

            gridAdapter.GridviewAdapterAdd(SubCategoryActivity.this,
                    list);
            runOnUiThread(returnRes);

        }

    }
}

private class getSubCategory extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... url) {
        // TODO Auto-generated method stub
        return BaseActivity.jsonParser.makeHttpRequest(url[0], "POST",
                nameValuePairs);

    }

    @Override
    protected void onProgressUpdate(Void... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        try {
            jsonArray = new JSONArray(result);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        SubCat = new String[jsonArray.length()][2];
        for (int i = 0; i < jsonArray.length(); i++) {

            JSONObject jsonObjet;

            try {

                jsonObjet = jsonArray.getJSONObject(i);
                SubCat[i][0] = String.valueOf(jsonObjet.getInt("id"));
                SubCat[i][1] = jsonObjet.getString("title_fa");

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO: handle exception
                e.toString();

            }

        }

        pagerAdapter = new MyPagerAdapter();

        pager.setAdapter(pagerAdapter);
        // pager.setCurrentItem(SubCat.length-1);

        // final int pageMargin = (int) TypedValue.applyDimension(
        // TypedValue.COMPLEX_UNIT_DIP, 30, getResources()
        // .getDisplayMetrics());
        // pager.setPageMargin(pageMargin);

        // pager.setCurrentItem(0);
        // pager.setOffscreenPageLimit(0);



        tabs.setViewPager(pager);
        tabs.setTextSize(20);
        tabs.setTypeface(BaseActivity.font, Typeface.NORMAL);

        list = new ArrayList<HashMap<String, String>>();
        nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("getAdvertise", "true"));
        nameValuePairs
                .add(new BasicNameValuePair("subCatId", SubCat[0][0]));

        new getSubCategoryObjects().execute(url2);

    }
}

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);

    intent = getIntent();

    tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
    pager = (ViewPager) findViewById(R.id.pager);

    tabs.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
            // TODO Auto-generated method stub

            recordNum = 0;
            totalItems = 0;
            pageNum = 1;
            //loadingMore = false;
            jsonArray = new JSONArray();
            list = new ArrayList<HashMap<String, String>>();
            nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("getAdvertise",
                    "true"));
            nameValuePairs.add(new BasicNameValuePair("subCatId",
                    SubCat[arg0][0]));

            // Activity myActivity = getActivity();
            // if (myActivity instanceof SubCategoryActivity) {
            new getSubCategoryObjects().execute(url2);

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }
    });

    inflator = SubCategoryActivity.this.getLayoutInflater();

    jsonArray = new JSONArray();
    nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("getSubCategory", "true"));
    nameValuePairs.add(new BasicNameValuePair("catId", intent
            .getStringExtra("id")));

    new getSubCategory().execute(url);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    getSupportActionBar().setDisplayShowTitleEnabled(false);
    getSupportActionBar().setDisplayShowCustomEnabled(true);

    tvCustomTitle = new TextView(this);
    tvCustomTitle.setText(intent.getStringExtra("title"));
    LinearLayout ll = new LinearLayout(this);
    LinearLayout.LayoutParams para = new LinearLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    para.setMargins(0, 0, 0, 0); // left,top,right, bottom
    para.gravity = Gravity.CENTER_VERTICAL;
    tvCustomTitle.setTypeface(BaseActivity.font);
    Configuration config = getResources().getConfiguration();
    if (Build.VERSION.SDK_INT >= 13) {

        if (config.smallestScreenWidthDp >= 600) {
            tvCustomTitle.setTextSize(22);
        } else {
            tvCustomTitle.setTextSize(14);
        }
    } else {
        tvCustomTitle.setTextSize(14);
    }

    tvCustomTitle.setTextColor(Color.WHITE);
    ll.addView(tvCustomTitle, para);
    getSupportActionBar().setCustomView(ll);

    changeColor(intent.getIntExtra("color", Color.parseColor("#FF666666")));

}

private void changeColor(int newColor) {

    tabs.setIndicatorColor(newColor);

    // change ActionBar color just if an ActionBar is available

    Drawable colorDrawable = new ColorDrawable(newColor);
    Drawable bottomDrawable = getResources().getDrawable(
            R.drawable.actionbar_bottom);
    LayerDrawable ld = new LayerDrawable(new Drawable[] { colorDrawable,
            bottomDrawable });

    getSupportActionBar().setBackgroundDrawable(ld);

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

}

public class MyPagerAdapter extends PagerAdapter {

    GridviewAdapter gridAdapter;

    public MyPagerAdapter(GridviewAdapter gridAdapter) {
        // TODO Auto-generated constructor stub
        this.gridAdapter = gridAdapter;
    }

    public MyPagerAdapter() {
        // TODO Auto-generated constructor stub

    }

    public Object instantiateItem(View collection, int position) {

        View rootView = inflator.inflate(
                R.layout.fragment_sub_category_objects, null);

        gridViewSubCategory = (GridView) rootView
                .findViewById(R.id.gridViewSubCategory);
        //progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
        relativeLayoutLoadingMore = (RelativeLayout) rootView.findViewById(R.id.relativeLayoutLoadingMore);

        gridViewSubCategory.setAdapter(gridAdapter);

        gridViewSubCategory
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent,
                            View view, int position, long id) {
                        // TODO Auto-generated method stub

                        BaseActivity.cd = new ConnectionDetector(
                                SubCategoryActivity.this);
                        BaseActivity.isInternetPresent = BaseActivity.cd
                                .isConnectingToInternet();

                        if (BaseActivity.isInternetPresent) {

                            Intent i = new Intent(SubCategoryActivity.this,
                                    SubCategoryActivity.class);
                            i.putExtra("id", ((TextView) view
                                    .findViewById(R.id.textViewId))
                                    .getText().toString());
                            i.putExtra(
                                    "color",
                                    i.getIntExtra("color",
                                            Color.parseColor("#FF666666")));
                            startActivity(i);
                        } else {
                            Toast.makeText(
                                    SubCategoryActivity.this,
                                    "به اینترنت متصل نیستید، به اینترنت متصل شده و دوباره امتحان کنید.",
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                });

        gridViewSubCategory.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view,
                    int scrollState) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {
                // TODO Auto-generated method stub

                // save index and top position

                // what is the bottom iten that is visible
                int lastInScreen = firstVisibleItem + visibleItemCount;

                // is the bottom item visible & not loading more already ?
                // Load
                // more !
                if ((lastInScreen == totalItemCount) && !(loadingMore)
                        && recordNum > 1) {
                    recordNum--;
                    pageNum++;
                    relativeLayoutLoadingMore.setVisibility(View.VISIBLE);
                    Thread thread = new Thread(null, loadMoreGridItems);
                    thread.start();
                }

            }
        });

        ((ViewPager) collection).addView(rootView, 0);
        return rootView;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return SubCat[position][1];
    }

    @Override
    public int getCount() {
        return SubCat.length;
    }

    @Override
    public void destroyItem(View collection, int position, Object view) {
        ((ViewPager)collection).removeView((RelativeLayout) view);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((RelativeLayout) object);
    }

}

// Runnable to load the items
private Runnable loadMoreGridItems = new Runnable() {
    @Override
    public void run() {
        // Set flag so we cant load new items 2 at the same time
        loadingMore = true;

        // Reset the array that holds the new items
        list = new ArrayList<HashMap<String, String>>();
        nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("getAdvertise", "true"));
        nameValuePairs
                .add(new BasicNameValuePair("subCatId", SubCat[pager.getCurrentItem()][0]));

        nameValuePairs.add(new BasicNameValuePair("pageNum", String
                .valueOf(pageNum)));

        new getSubCategoryObjects().execute(url3);

    }
};

// Since we cant update our UI from a thread this Runnable takes care of
// that!
private Runnable returnRes = new Runnable() {
    @Override
    public void run() {

        //pager.requestLayout();
        relativeLayoutLoadingMore.setVisibility(View.GONE);
        gridViewSubCategory.setAdapter(gridAdapter);
        //gridAdapter.notifyDataSetChanged();

        // Done loading more.
        loadingMore = false;


    }
};

public class GridviewAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<HashMap<String, String>> list;
    HashMap<String, String> tempMap;

    public GridviewAdapter(Activity activity,
            ArrayList<HashMap<String, String>> list) {

        this.activity = activity;

        this.list = list;

    }

    public void GridviewAdapterAdd(Activity activity,
            ArrayList<HashMap<String, String>> list) {

        this.activity = activity;

        for (int i = 0; i < list.size(); i++)
            this.list.add(list.get(i));

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        LayoutInflater inflator = activity.getLayoutInflater();

        View vi = convertView;
        if (convertView == null)
            vi = inflator.inflate(R.layout.gridview_sub_category_row, null);

        TextView id = (TextView) vi.findViewById(R.id.textViewId);
        TextView title = (TextView) vi.findViewById(R.id.textViewTitle);
        ImageView imageViewSubCat = (ImageView) vi
                .findViewById(R.id.imageViewSubCat);
        TextView price = (TextView) vi.findViewById(R.id.textViewPrice);
        TextView date = (TextView) vi.findViewById(R.id.textViewDate);
        RelativeLayout textBackground = (RelativeLayout) vi
                .findViewById(R.id.relativeLayoutText);

        tempMap = new HashMap<String, String>();
        tempMap = list.get(position);

        id.setText(tempMap.get("id"));
        textBackground.setBackgroundColor(intent.getIntExtra("color",
                Color.parseColor("#FF666666")));
        title.setText(tempMap.get("title"));
        price.setText(tempMap.get("price"));
        date.setText(tempMap.get("date"));
        title.setTypeface(BaseActivity.font);
        price.setTypeface(BaseActivity.font);
        date.setTypeface(BaseActivity.font);

        // File cachedImg = ImageLoader.getInstance().getDiscCache()
        // .get(picUrl + tempMap.get("logo") + ".jpg");

        // if (cachedImg.exists())
        // cachedImg.delete();

        ImageLoader.getInstance().displayImage(
                BaseActivity.picUrl + tempMap.get("image") + ".jpg",
                imageViewSubCat);

        return vi;
    }
}
4

0 回答 0