简体   繁体   中英

Issue in accessing activity class variable inside pager adapter class in Android

I have an arraylist of hashmaps inside the fragment activity class like this. This is inside OnCreate method.

   try {
       pp = new Parser(getQuery());
       productData = pp.getData(asynctask, getQuery());
       Log.v("data size:", ""+productData.size()+"");
    } catch (URISyntaxException e) {
    e.printStackTrace();
        } 
    public ArrayList<HashMap<String, String>> getProductData()
      {
      return this.productData;
      }

Here it works fine and data loaded correctly. And the variable productData is declared as public.

Here is my fragment adapter class:

   public class ProductViewPagerAdapter extends FragmentPagerAdapter {
      ProductViewActivity productViewActivity = new ProductViewActivity();;
        public ProductViewPagerAdapter(FragmentManager fm) {
    super(fm);
    }

   @Override
    public Fragment getItem(int i) {
        int temp = productViewActivity.getProductData().size();
        Log.v("size:",""+temp+""); 
        Fragment fragment = new ProductViewFragment();
        Bundle args = new Bundle();
        args.putInt(ProductViewFragment.ARG_SECTION_NUMBER, i + 1);
        fragment.setArguments(args);
        return fragment;
       }

Here the size gives 0. That ends up in Null pointer exception. Where is the issue here?

That's your problem:

ProductViewActivity productViewActivity = new ProductViewActivity(); You need to pass the instance of the Activity in the constructor of ProductViewPagerAdapter

public ProductViewPagerAdapter(FragmentManager fm, ProductViewPagerAdapter activity) {
    super(fm);
    mActivity = activity;
    }

OR set it explicitly with a setter function.

public void setActivity( ProductViewPagerAdapter activity) {
        mActivity = activity;
        }

Then change

int temp = productViewActivity.getProductData().size();

To:

int temp = mActivity.getProductData().size();

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM