ViewPager InstatiateItem方法多次调用

时间:2015-04-17 10:22:41

标签: android

您好我正在尝试将视图寻呼机添加到我的应用程序中。我已经将我想要的所有细节加载到视图寻呼机中,包括Map(我在某些部分显示它)。但是instantiateItem方法被多次调用。我在哪里弄错了..帮助我。以下是我发布的代码。

public class ViewPagerAdapter extends PagerAdapter
{
Activity context;
List<ListDetails> products;
LayoutInflater inflater;
private String user_latitude;
private String user_longitude;
private double to_latitude;
private Location nwLocation;
AppLocationService appLocationService;
private double to_longitude;
private static View itemView;

private CopyOnWriteArrayList<ListDetails> ListItemsData;
private static GMapV2Direction gmapdirection;
private static GoogleMap gmap;
private JSONObject SaveOfferObj;

 static final String ARG_POSITION = "position";
    int mCurrentPosition = -1;
    private TextView txt_offer;
    private TextView txt_distance;
    private TextView txt_shop;
    private TextView txt_category;
    private TextView txt_couponcode;
    private RatingBar rat_user;
    private TextView txt_enddate;
 // private View alertLayout;
  private static View alertLayout;
ListDetails product;
private HorizontalListView swipelisview;
private Repo repoObject;

ImageView viewdetails;
TableLayout tbldetails;
public ViewPagerAdapter(Context context, List<ListDetails> products, android.app.FragmentManager fragmentManager) {
    this.context = (Activity) context;
    this.products = products;

}

@Override
public int getCount() {
    return products.size();
}

public ListDetails getItem(int position) {
    return products.get(position);
}

/* public NotificationViewPagerAdapter(FragmentManager fm) { 
        super(fm); 
    } 

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

    @Override 
    public Fragment getItem(int position) {
        return NotificationFragment.newInstance(_context, _notificationViewPager.getNotification(position), position, _notificationViewPager.getTotalNotifications());
    } */

  @Override 
    public int getItemPosition(Object object) {
        int index = products.indexOf(object);
        if(index >= 0){
            return index;
        }else{ 
            return PagerAdapter.POSITION_NONE;
        } 
    } 

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

@Override
public boolean isViewFromObject(View view, Object object) {
    if(object != null){
        return ((FrameLayout)object) == view;
          //return ((FrameLayout)object).getRootView() == view;
    }else{
        return false;
    }
    /*if(object != null){
        return ((Fragment)object).getView() == view;
    }else{
        return false;
    }*/
}



@SuppressLint("InflateParams")
@Override
public  Object instantiateItem(ViewGroup container, int position) {


        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        LayoutInflater li = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if(itemView==null)
        {
            if(alertLayout==null)

             alertLayout = li.inflate(R.layout.map_dialog,
                    null);

        }
         /*if (itemView != null) { 
                ViewGroup parentViewGroup = (ViewGroup) itemView.getParent();
                if (parentViewGroup != null) {
                    parentViewGroup.removeView(itemView);
                    //((ViewPager) container).removeView(itemView);
                } 
            } */

        try { 

            //if(itemView == null)
            //{
                inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                itemView = inflater.inflate(R.layout.single,container, false);
            //}


        } catch (InflateException e) {


        }  
            try {


             txt_offer = (TextView) itemView
                    .findViewById(R.id.Offer_edittext); 
             txt_distance = (TextView) itemView
                    .findViewById(R.id.distance_edittext);
            /*TextView txt_area = (TextView) rootView
                    .findViewById(R.id.area_edittext);*/
             txt_shop = (TextView) itemView
                    .findViewById(R.id.Shop_edittext);


          tbldetails = (TableLayout) itemView.findViewById(R.id.tablevielw);


             rat_user = (RatingBar) itemView.findViewById(R.id.user_ratingbar);

              viewdetails  = (ImageView) itemView.findViewById(R.id.btn_details);

                viewdetails.setOnClickListener(new View.OnClickListener() {

                     @Override
                     public void onClick(View v) {
                         if (tbldetails.getVisibility()==View.GONE){
                             viewdetails.setBackgroundResource(R.drawable.collapse); 
                             expand();
                         }else{
                             viewdetails.setBackgroundResource(R.drawable.expand);
                             collapse();
                         }
                     }
                 });


            RatingBar rat_user = (RatingBar) itemView.findViewById(R.id.user_ratingbar);



             //ImageView map = (ImageView) itemView.findViewById(R.id.btn_map);



            swipelisview = (HorizontalListView) itemView.findViewById(R.id.gridview);

            swipelisview.setOnItemClickListener(new OnItemClickListener() { 

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) { 


             appLocationService = new AppLocationService(context);

                    nwLocation = appLocationService
                            .getLocation(LocationManager.NETWORK_PROVIDER);
                    if (nwLocation == null) {
                        nwLocation = new Location("");
                        nwLocation.setLatitude(17.4165);
                        nwLocation.setLongitude(78.4382);
                    }

                    ListDetails mDetails = ListItemsData.get(position);

                    user_latitude = Double.toString(nwLocation.getLatitude());
                    user_longitude = Double.toString(nwLocation.getLongitude());

                    to_latitude =mDetails.getLat();
                    to_longitude = mDetails.getLng(); 

                    String AreaName = mDetails.getAreaName();
                    String ShopName = mDetails.getShopName();

                    String ShopID = mDetails.getShopID();

                    String OfferName = mDetails.getDeal();
                    float Distance = mDetails.getDistance();
                    String PromoCode = mDetails.getPromoCode();

                    String PostedDate = mDetails.getPostedDate();
                    String EndDate = mDetails.getOfferEndDate();

                    String Category = mDetails.getCategoryName();

                    String OfferId = mDetails.getOfferID();

                    TextView txt_offer = (TextView) itemView
                            .findViewById(R.id.Offer_edittext); 
                    TextView txt_distance = (TextView) itemView
                            .findViewById(R.id.distance_edittext);
                    /*TextView txt_area = (TextView) rootView
                            .findViewById(R.id.area_edittext);*/
                    TextView txt_shop = (TextView) itemView
                            .findViewById(R.id.Shop_edittext);

                    RatingBar rat_user = (RatingBar) itemView.findViewById(R.id.user_ratingbar);

                    TextView txt_posteddate = (TextView) itemView
                            .findViewById(R.id.offerPosted_edittext);
                    TextView txt_enddate = (TextView) itemView
                            .findViewById(R.id.OfferEnd_edittext);

                    TextView txt_category = (TextView) itemView
                            .findViewById(R.id.category_edittext);


                    TextView txt_couponcode = (TextView) itemView
                            .findViewById(R.id.Coupon_edittext);

                    final ArrayList<String> ImageArrayList = new ArrayList<String>();

                    String ImageNameStr = mDetails.getImageName1();
                    final String[] ImageNameArr = ImageNameStr.split(",");

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

                    ViewPager viewPager = (ViewPager) itemView
                            .findViewById(R.id.view_pager);
                    ImageAdapter adapter = new ImageAdapter(context,
                            ImageArrayList);
                    viewPager.setAdapter(adapter);

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



                    txt_offer.setText(OfferName);
                    txt_distance.setText(Distance+" KM Away"); 
                    //txt_area.setText(AreaName);
                    txt_shop.setText(ShopName+" , "+ AreaName);
                    txt_couponcode.setText(PromoCode);
                    txt_category.setText(Category);
                    txt_posteddate.setText(PostedDate);
                    txt_enddate.setText(EndDate);
                    rat_user.setRating(3f);


                    LoadPlaceDetails();


                }
            });

            Button btnrating = (Button) itemView.findViewById(R.id.btn_rating);

             btnrating.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        try {
                            Rating_Listview mRating_Listview = new Rating_Listview();
                            Bundle PFBundel = new Bundle();
                            PFBundel.putString("Offer",product.getDeal());
                            PFBundel.putString("OfferID",product.getOfferID());

                            android.app.FragmentManager fragment = context.getFragmentManager();
                            mRating_Listview.setArguments(PFBundel);
                            fragment.beginTransaction()
                                    .replace(R.id.frame_container, mRating_Listview)
                                    .commit();
                            LoadActivity.CURRENTFRAGMENT = EnumModuleTags.Rating_Listview;
                            ModuleFragmentBackStackingClass.AddtoStack(
                                    mRating_Listview,
                                    EnumModuleTags.Rating_Listview,
                                    "RightPlaceRightTime");
                        } catch (Exception e) {
                            Toast.makeText(context, e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }

                    }
                });

            TextView txt_posteddate = (TextView) itemView
                    .findViewById(R.id.offerPosted_edittext);
             txt_enddate = (TextView) itemView
                    .findViewById(R.id.OfferEnd_edittext);

             txt_category = (TextView) itemView
                    .findViewById(R.id.category_edittext);


             txt_couponcode = (TextView) itemView
                    .findViewById(R.id.Coupon_edittext);

              product = (ListDetails) getItem(position);

            final ArrayList<String> ImageArrayList = new ArrayList<String>();

            String ImageNameStr = product.getImageName1();
            final String[] ImageNameArr = ImageNameStr.split(",");

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

            ViewPager viewPager = (ViewPager) itemView
                    .findViewById(R.id.view_pager);
            ImageAdapter adapter = new ImageAdapter(context,
                    ImageArrayList);
            viewPager.setAdapter(adapter);

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



             appLocationService = new AppLocationService(context);

                nwLocation = appLocationService
                        .getLocation(LocationManager.NETWORK_PROVIDER);
                if (nwLocation == null) {
                    nwLocation = new Location("");
                    nwLocation.setLatitude(17.4165);
                    nwLocation.setLongitude(78.4382);
                }

                user_latitude = Double.toString(nwLocation.getLatitude());
                user_longitude = Double.toString(nwLocation.getLongitude());

            to_latitude = product.getLat();

            to_longitude = product.getLng();

            txt_offer.setText(product.getDeal());
            txt_distance.setText(product.getDistance()+" KM Away"); 
            //txt_area.setText(AreaName);
            txt_shop.setText(product.getShopName()+" , "+ product.getAreaName());
            txt_couponcode.setText(product.getPromoCode());
            txt_category.setText(product.getCategoryName());
            txt_posteddate.setText(product.getPostedDate());
            txt_enddate.setText(product.getOfferEndDate());
            rat_user.setRating(3f);

            final FloatingActionsMenu fmenu = (FloatingActionsMenu) itemView.findViewById(R.id.multiple_actions);
             final FloatingActionsMenu fmenu1 = (FloatingActionsMenu) itemView.findViewById(R.id.multiple_actions1);
             fmenu.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        fmenu1.collapse();
                    }

                    });



             fmenu1.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        fmenu.collapse();
                    }

                    });





            //}


            ((ViewPager) container).addView(itemView , 0); 

            //return itemView;
        } catch (Exception e) {
            PostLogcatErorrs(e);
        }



    return itemView;
}


@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    // Remove viewpager_item.xml from ViewPager
    ((ViewPager) container).removeView((FrameLayout) object);


    /* android.app.FragmentTransaction ft=fm.beginTransaction(); 
        ft.remove((Fragment) object);
        ft.commit(); */

      Fragment f = context.getFragmentManager().findFragmentById(R.id.map);
        if (f != null)  
            context.getFragmentManager().beginTransaction().remove(f).commit();

}

private void LoadPlaceDetails() {
    try {
        // TODO Auto-generated method stub

        // Your code goes here
        final LatLng fromPosition = new LatLng(
                Double.parseDouble(user_latitude),
                Double.parseDouble(user_longitude));
        final LatLng toPosition = new LatLng(to_latitude,
                to_longitude);

        gmapdirection = new GMapV2Direction();
        FragmentManager fm = ((FragmentActivity) context)
                .getSupportFragmentManager();

        gmap = ((SupportMapFragment) fm.findFragmentById(R.id.map)).getMap(); 
        gmap.clear();

        LatLng coordinates = new LatLng(
                (Double.parseDouble(user_latitude) + to_latitude) / 2,
                (Double.parseDouble(user_longitude) + to_latitude) / 2);
        gmap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));

        gmap.addMarker(new MarkerOptions()
                .position(fromPosition)
                .title("Current Location")
                .icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
        gmap.addMarker(new MarkerOptions()
                .position(toPosition)
                .title("")
                .icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_VIOLET))); 

        Document doc = gmapdirection.getDocument(fromPosition, toPosition,
                GMapV2Direction.MODE_DRIVING, context);
    } catch (NumberFormatException e) {
        PostLogcatErorrs(e);
    }

}

public static void Newe(Document doc) {
    // TODO Auto-generated method stub
    ArrayList<LatLng> directionPoint = gmapdirection.getDirection(doc);
    PolylineOptions rectLine = new PolylineOptions().width(3).color(
            Color.RED);

    for (int i = 0; i < directionPoint.size(); i++) {
        rectLine.add(directionPoint.get(i));
    }

    gmap.addPolyline(rectLine);
}

private void GetOfferShopList() {
    try {
        if(SplashScreen.isOnline)
        {
        final Location CurrentLocation = new Location("point A");     
        CurrentLocation.setLatitude(Double.parseDouble(user_latitude)); 
        CurrentLocation.setLongitude(Double.parseDouble(user_longitude));
        ListItemsData = new CopyOnWriteArrayList<ListDetails>(); 
        // Creating volley request obj
                JsonObjectRequest movieReq = new JsonObjectRequest(LoadActivity.BaseUri + "GetAllOffer?type="+product.getCategoryName(),
                        null, new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                //Log.d(TAG, response.toString());

                                JSONArray GetMG_AppointmentRequestResult = null;
                                try {
                                    GetMG_AppointmentRequestResult = response.getJSONArray("GetAllOfferResult");
                                } catch (JSONException e1) {
                                    Toast.makeText(context, 
                                            e1.getMessage(), Toast.LENGTH_LONG).show();
                                    e1.printStackTrace();
                                }
                                // Parsing json
                                for (int i = 0; i < GetMG_AppointmentRequestResult.length(); i++) {
                                    try {

                                        JSONObject obj = GetMG_AppointmentRequestResult.getJSONObject(i);

                                        ListDetails ListModelObj = new ListDetails();

                                        Location RetailerLocation = new Location("point B");
                                        RetailerLocation.setLatitude(Double.parseDouble(obj
                                                .getString("Lat"))); 
                                        RetailerLocation.setLongitude(Double.parseDouble(obj
                                                .getString("Lng")));
                                        float distance = CurrentLocation.distanceTo(RetailerLocation)/1000;

                                        float val = (float)Math.round(distance * 10) / 10;


                                        ListModelObj.setDistance(val);

                                        ListModelObj.setPosition_id(Integer.parseInt(obj.getString("ShopRegID")));
                                        ListModelObj.setShopName(obj.getString("ShopName"));
                                        ListModelObj.setDescription(obj.getString("OfferName"));
                                        ListModelObj.setLat(Double.parseDouble(obj.getString("Lat")));
                                        ListModelObj.setLng(Double.parseDouble(obj.getString("Lng")));                                          
                                        ListModelObj.setDeal(obj.getString("Deal")); 
                                        ListModelObj.setPromoCode(obj.getString("PromoCode"));
                                        ListModelObj.setAreaName(obj.getString("AreaName"));

                                        ListModelObj.setOfferStatus(obj.getString("OfferStatus"));
                                        ListModelObj.setCategoryName(obj.getString("CategoryType"));

                                        ListModelObj.setPostedDate(obj
                                                .getString("OfferStartDate"));


                                        ListModelObj.setOfferEndTime(obj
                                                .getString("OfferEndTime"));

                                        ListModelObj.setOfferEndDate(obj
                                                .getString("OfferEndDate"));

                                        ListModelObj.setOfferID(obj
                                                .getString("OfferID"));


                                        ListModelObj.setImageName1(obj.getString("ImageName"));
                                        //ListModelObj.setImageName2(obj.getString("ImageName2"));
                                        //ListModelObj.setImageName3(obj.getString("ImageName3"));

                                        String abc = obj.getString("ImageName");
                                        String[] xyz = abc.split(",");

                                        ListModelObj.setListImage(LoadActivity.BaseUriImg 
                                                                                        + xyz[0]);  
                                        ListItemsData.add(ListModelObj);


                                        /*offertable Offers = null;

                                        Repo repoObject = LoadActivity.getRepo();

                                        Offers = new offertable();

                                        Offers.setOfferID(Integer.parseInt(obj.getString("OfferID")));
                                        Offers.setShopRegID(Integer.parseInt(obj.getString("ShopRegID")));
                                        Offers.setShopName(obj.getString("ShopName"));
                                        Offers.setTime(obj.getString("Time"));
                                        Offers.setCreatedDate(obj.getString("CreatedDate"));
                                        Offers.setModifyDate(obj.getString("ModifyDate"));
                                        Offers.setOfferStartDate(obj.getString("OfferStartDate"));
                                        Offers.setOfferEndDate(obj.getString("OfferEndDate"));
                                        Offers.setOfferStartTime(obj.getString("OfferStartTime"));
                                        Offers.setOfferEndTime(obj.getString("OfferEndTime"));
                                        Offers.setDeal(obj.getString("Deal"));
                                        Offers.setDescription(obj.getString("Description"));
                                        Offers.setPromoCode(obj.getString("PromoCode"));
                                        Offers.setImageName(obj.getString("ImageName"));
                                        Offers.setOfferStatus(Integer.parseInt(obj.getString("OfferStatus")));
                                        Offers.setRowStatus("A");
                                        Offers.setAreaName(obj.getString("AreaName"));
                                        Offers.setLat(obj.getString("Lat"));
                                        Offers.setLng(obj.getString("Lng"));
                                        Offers.setCategoryType(obj.getString("CategoryType"));

                                        Offers.setDistance(String.valueOf(val));
                                        //Offers.setTimeTaking(distance1);

                                        repoObject.roffertable.save(Offers);*/

                                    } catch (JSONException e) {
                                        Toast.makeText(context, 
                                                e.getMessage(), Toast.LENGTH_LONG).show();
                                        e.printStackTrace();
                                    }
                                }
                                // notifying list adapter about data changes
                                // so that it renders the list view with updated data


                                CustomGridAdapter customAdapter =new CustomGridAdapter(context,ListItemsData);
                                swipelisview.setAdapter(customAdapter);


                                customAdapter.notifyDataSetChanged();

                            }
                        }, new Response.ErrorListener() { 
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                //VolleyLog.d(TAG, "Error: " + error.getMessage());

                            }
                        });

                AppController.getInstance().addToRequestQueue(movieReq);
        }
           else {

                repoObject = LoadActivity.getRepo();

                List<offertable> alloffers = repoObject.roffertable.getAlloffersByFilter(product.getCategoryName());


                ListItemsData = new CopyOnWriteArrayList<ListDetails>();
                if (alloffers != null) {
                    for (offertable s : alloffers) {
                        final ListDetails ListModelObj = new ListDetails();

                        ListModelObj.setTime(s.getTimeTaking());

            ListModelObj.setDistance(Float.parseFloat(s.getDistance()));

            ListModelObj.setPosition_id(s.getShopRegID());
            ListModelObj.setShopName(s.getShopName());
            ListModelObj.setDescription(s.getDescription());
            ListModelObj.setLat(Double.parseDouble(s.getLat()));
            ListModelObj.setLng(Double.parseDouble(s.getLng()));
            ListModelObj.setDeal(s.getDeal()); 
            ListModelObj.setPromoCode(s.getPromoCode());
            ListModelObj.setAreaName(s.getAreaName());

            ListModelObj.setPostedDate(s.getOfferStartDate()); 


            ListModelObj.setOfferEndTime(s.getOfferEndTime());

            ListModelObj.setOfferEndDate(s.getOfferEndDate());

            ListModelObj.setShopID(String.valueOf(s.getShopRegID()));

            ListModelObj.setOfferStatus(String.valueOf(s.getOfferStatus()));

            ListModelObj.setCategoryName(s.getCategoryType());



            ListModelObj.setOfferID(String.valueOf(s.getOfferID()));

            ListModelObj.setImageName1(s.getImageName());  

            String abc = s.getImageName(); 
            String[] xyz = abc.split(",");

            ListModelObj
                    .setListImage(LoadActivity.BaseUriImg + xyz[0]);

            ListItemsData.add(ListModelObj); 

                    }
                    CustomGridAdapter customAdapter =new CustomGridAdapter(context,ListItemsData);
                    swipelisview.setAdapter(customAdapter);

                    customAdapter.notifyDataSetChanged();
                    //progresdialog.dismiss();


                }

           }
    } catch (Exception e1) {
        Toast.makeText(context, 
                e1.getMessage(), Toast.LENGTH_LONG).show();
        e1.printStackTrace();
        //java.lang.NullPointerException: Attempt to invoke virtual method 
        //'void customlistviewvolley.AppController.addToRequestQueue(com.android.volley.Request)' 
        //on a null object reference
    }
}

}

1 个答案:

答案 0 :(得分:1)

您的布局代码是什么样的?

当我在布局中实例化Fragment然后在onCreate()方法

中实例化时,我遇到了类似的问题