android 中数据更改时,查看寻呼机第一个和第二个片段数据未更新?

View pager first and second fragment data is not updating when data changed in android?

我正在使用查看寻呼机(动态)来显示来自服务的数据。它工作正常,但每当我再次调用该服务时,视图寻呼机中的数据需要刷新并使用新数据(来自服务)进行更新。

视图寻呼机中的所有片段都在用新数据刷新,但是视图寻呼机的前两个片段没有用新数据更新,这两个片段(第一个和第二个)只显示以前的数据。请任何人帮助我。

我的代码:

RechargeplansActivity.java:

public class RechargeplansActivity  extends FragmentActivity /*implements RechargePlansFragment.UserInterface*/ {
    static final String TAG = RechargeplansActivity.class.getSimpleName();
    SectionsPagerAdapter mSectionsPagerAdapter;
    ViewPager mViewPager;
    Intent intent;
    private ArrayList<String> mPlanNamesList;
    private ArrayList<BrowsePlan> mBrowsePlansList;
    TextView tx_network;
    Dialog message_dialg;
    Context context;
    String operatorid,circleid;

    Map<String, ArrayList<BrowsePlan>> mBrowsePlansMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rechargeplans);

        context = this;

        intent = getIntent();
        setPlan_types(new ArrayList<String>());
        setBrowseplans(new ArrayList<BrowsePlan>());
        mBrowsePlansMap = new HashMap<String, ArrayList<BrowsePlan>>();
        //db = DatabaseHandler.getInstance(getApplicationContext());
        initUI();




        operatorid=intent.getStringExtra("op_id");
        circleid=intent.getStringExtra("cir_id");



        executeBrowsePlans();
        tx_network.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Browseplans_dialog();
            }
        });


    }

    /* It is used for initialization */
    private void initUI() {
        tx_network = (TextView) findViewById(R.id.tx_network);

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        //iv_back = (ImageView) findViewById(R.id.iv_back);
        // Create the adapter that will return a fragment
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        mViewPager.setAdapter(mSectionsPagerAdapter);

    }


    /* Data getting from the service */
    private void executeBrowsePlans() {
        ServiceClient serviceClient = ServiceUtil.getServiceClient();



        mProgressDialog.show();
        serviceClient.getPlans_v2(operatorid, circleid, getshowPlansCallback);

    }



    /**
     * @return the al_browseplans
     */
    public ArrayList<BrowsePlan> getBrowseplans(String key) {
        if (key == null && !mPlanNamesList.contains(key)) {
            return new ArrayList<BrowsePlan>();
        }
        return mBrowsePlansMap.get(key);
    }

    /**
     * @return the al_browseplans
     */
    public ArrayList<BrowsePlan> getBrowseplans() {
        return mBrowsePlansList;
    }

    /**
     * @param al_browseplans
     *            the al_browseplans to set
     */
    public void setBrowseplans(ArrayList<BrowsePlan> al_browseplans) {
        this.mBrowsePlansList = al_browseplans;
    }

    protected void traceD(String msg) {

        // Log.d(TAG, msg);
    }

    /**
     * @return the plan_types
     */
    public ArrayList<String> getPlan_types() {
        return mPlanNamesList;
    }

    /**
     * @param plan_types
     *            the plan_types to set
     */
    public void setPlan_types(ArrayList<String> plan_types) {
        Log.v("Tag_plantype", "" + plan_types.size());

        this.mPlanNamesList = plan_types;
    }

    Callback<JsonObject> getshowPlansCallback = new Callback<JsonObject>() {

        @Override
        public void failure(RetrofitError arg0) {
            // TODO Auto-generated method stub
            dismissProgress();
        }

        @Override
        public void success(JsonObject resultUserInfo, Response arg1) {
            traceD(" Browse Plans" + resultUserInfo.toString());
            dismissProgress();



            // String
            // planTypes=resultUserInfo.get("Plantypes").getAsString();
            // mPlanNamesList.addAll(Arrays.asList(planTypes.split(",")));
            // mSectionsPagerAdapter.notifyDataSetChanged();
            if (resultUserInfo.has("Status")) {
                String Status = resultUserInfo.get("Status")
                        .getAsString();
                if(Status.equalsIgnoreCase("false")){
                    dismissProgress();
                }
                else if(Status.equalsIgnoreCase("true")) {

                    JsonArray array = resultUserInfo.get("Plans")
                            .getAsJsonArray();

                    Type type = new TypeToken<ArrayList<BrowsePlan>>() {
                    }.getType();
                    Gson gson = new Gson();

                    getBrowseplans().addAll(
                            (Collection<? extends BrowsePlan>) gson.fromJson(array,
                                    type));
                    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {

                        @Override
                        protected Void doInBackground(Void... params) {
                            Log.v("TAG_PLANS_1",""+mBrowsePlansList.size());

                            if (mBrowsePlansList.size() > 0) {
                                Log.v("TAG_PLANS",""+mBrowsePlansList);


                                for (BrowsePlan bl : mBrowsePlansList) {
                                    if (mBrowsePlansMap.get(bl.getPlanType()) == null) {
                                        mBrowsePlansMap.put(bl.getPlanType(), new ArrayList<BrowsePlan>());
                                    }
                                    mBrowsePlansMap.get(bl.getPlanType()).add(bl);
                                    //setBrowseplans(mBrowsePlansMap.get(bl.getPlanType()));
                                    Log.v("TAG_PLANS_map", "" +  (bl.getPlanType().toString())
                                    );
                                }




                            }


                            // mBrowsePlansList.clear();
                            for (Map.Entry<String, ArrayList<BrowsePlan>> entry : mBrowsePlansMap.entrySet()) {

                                mPlanNamesList.add(entry.getKey());
                            }
                            return null;
                        }

                        protected void onPostExecute(Void result) {

                            for(BrowsePlan bp: getBrowseplans()){
                                System.out.println("plan type post execute: "+bp.getPlanType()+"value: "+bp.getPlanValue());
                            }

                           // mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

                          //  mViewPager.setAdapter(mSectionsPagerAdapter);

                            mSectionsPagerAdapter.notifyDataSetChanged();
                            //mViewPager.setCurrentItem(4);
                        }

                        ;

                    };
                    task.execute();
                }

            }

        }
    };

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        dismissProgress();
    }

   /* @Override
    public void setBrowsePlansToRefresh(RechargePlansFragment.BrowsePalnsAdapter adapter, ListView listView) {
        //adapter = new BrowsePlansAdapter();

    }

    @Override
    public void setData(ArrayList<BrowsePlan> plans) {
        mBrowsePlansList.clear();
        mBrowsePlansList = plans;
    }
*/

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {
        private boolean doNotifyDataSetChangedOnce = false;

        public SectionsPagerAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        // Returns total number of pages
        @Override
        public int getCount() {
            if (doNotifyDataSetChangedOnce) {
                doNotifyDataSetChangedOnce = false;
                notifyDataSetChanged();
            }
            return getPlan_types().size();
        }

        // Returns the fragment to display for that page
        @Override
        public Fragment getItem(int position) {

            return RechargePlansFragment
                    .newInstance(mPlanNamesList.get(position));
        }

        // Returns the page title for the top indicator
        public CharSequence getPageTitle(int position) {
            return getPlan_types().get(position);
        }

        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

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

            return super.instantiateItem(container, position);
        }

        @Override
        public long getItemId(int position) {
            return super.getItemId(position);
        }
    }

    @Override
    public void onActivityResult(int arg0, int arg1, Intent arg2) {

        setResult(arg1, arg2);
        traceD("onActivityResult ");
        finish();
        super.onActivityResult(arg0, arg1, arg2);
    }

    void showProgress(int msgID) {

        dismissProgress();
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
        }
        if (mProgressDialog != null && !mProgressDialog.isShowing()) {

            mProgressDialog.setMessage(getResources().getString(msgID));
            mProgressDialog.show();
        }

    }

    void dismissProgress() {

        if (mProgressDialog != null && mProgressDialog.isShowing()) {

            mProgressDialog.dismiss();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        mSectionsPagerAdapter.notifyDataSetChanged();
    }
    void Browseplans_dialog( ) {

        message_dialg = new Dialog(this);
        Window window = message_dialg.getWindow();
        message_dialg.requestWindowFeature(Window.FEATURE_NO_TITLE);
        message_dialg.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        message_dialg.setContentView(R.layout.activity_selectdialog);
      Button  viewplans=(Button)message_dialg.findViewById(R.id.viewplans);
        viewplans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                operatorid = "5";
                circleid="1";
                mPlanNamesList.clear();
                mBrowsePlansList.clear();
                mBrowsePlansMap.clear();



                executeBrowsePlans();
                message_dialg.dismiss();
            }
        });


        window.setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        window.setGravity(Gravity.CENTER);


        message_dialg.setCancelable(true);



        message_dialg.show();


    }

}

RechargePlansFragment.java:

public class RechargePlansFragment extends Fragment {
    static final String ARG_KEY = "key";
    static final String TAG = RechargePlansFragment.class.getSimpleName();
    // Store instance variables
    ArrayList<BrowsePlan> mBrowseplans ;//= new ArrayList<BrowsePlan>();
    BrowsePalnsAdapter browsePlansAdapter;
    ListView lv_browseplans;
    View rootView;
    static String key;
    boolean flag = false;
    SharedPreferences m_sharedPreference;
    SharedPreferences.Editor m_editor;
    static  UserInterface objUserInterface;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
      //  objUserInterface = (UserInterface)activity;
    }

    public interface UserInterface{
        public void setBrowsePlansToRefresh(BrowsePalnsAdapter adapter, ListView listView);
       // public void setData(ArrayList<BrowsePlan> plans);
    }

    // newInstance constructor for creating fragment with arguments
    public static RechargePlansFragment newInstance(String key) {
        RechargePlansFragment fragmentFirst = new RechargePlansFragment();
        Bundle args = new Bundle();
        args.putString(ARG_KEY, key);

        //objUserInterface.setBrowsePlansToRefresh();
        fragmentFirst.setArguments(args);
        return fragmentFirst;
    }

    // Store instance variables based on arguments passed
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //((MobeRechargeApplication)getActivity().getApplication()).sendScreenName("Browse Plans");
        if (getArguments() != null) {
            key = getArguments().getString(ARG_KEY);
        }
        mBrowseplans = new ArrayList<BrowsePlan>();
        mBrowseplans.addAll(((RechargeplansActivity) getActivity()).getBrowseplans(key));
        Log.v("TAG_KEYYYYY",""+key + "  " +mBrowseplans.size()+ " planvalue " +mBrowseplans.get(0).getPlanValue());
        traceD(" key :" + key);



    }

    void traceD(String msg) {

        //Log.d(TAG, msg);
    }

    // Inflate the view for the fragment based on layout XML
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_browseplans, container,
                false);
        m_sharedPreference = getActivity().getSharedPreferences("save_details", Context.MODE_PRIVATE);
        m_editor = m_sharedPreference.edit();


        System.out.println("browse size:" + mBrowseplans.size());
        for(int i=0; i<mBrowseplans.size();i++){
            System.out.println(" Recharge plan type: "+mBrowseplans.get(i).getPlanType());
        }



        initUI();
        browsePlansAdapter = new BrowsePalnsAdapter(mBrowseplans);
        lv_browseplans.setAdapter(browsePlansAdapter);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        browsePlansAdapter.notifyDataSetChanged();
    }

    private void initUI() {
        lv_browseplans = (ListView) rootView.findViewById(R.id.lv_browseplans);
    }

    @SuppressWarnings("hiding")
    class BrowsePalnsAdapter extends BaseAdapter {
        ArrayList<BrowsePlan> allPlans;

        public BrowsePalnsAdapter(ArrayList<BrowsePlan> bplans){
            this.allPlans = bplans;

        }

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

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public int getViewTypeCount() {

            return getCount();
        }

        @Override
        public int getItemViewType(int position) {

            return position;
        }



        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view;
            ViewHolder viewHolder;
            Typeface custom_regular = Typeface.createFromAsset(getActivity().getAssets(),
                    "fonts/OpenSans-Regular.ttf");
            if (convertView == null) {
                viewHolder = new ViewHolder();
                view = LayoutInflater.from(getActivity()).inflate(
                        R.layout.plans_list_adapter, parent, false);
                viewHolder.tx_price = (TextView) view
                        .findViewById(R.id.planvalue_txt);
                viewHolder.tx_talktime = (TextView) view
                        .findViewById(R.id.plantalktime_txt);
                viewHolder.tx_validity = (TextView) view
                        .findViewById(R.id.planvalidity_txt);
                viewHolder.tx_plansdetails = (TextView) view
                        .findViewById(R.id.plansdetails_txt);
                viewHolder.tx_price.setTypeface(custom_regular);
                viewHolder.tx_talktime.setTypeface(custom_regular);
                viewHolder.tx_validity.setTypeface(custom_regular);
                viewHolder.tx_plansdetails.setTypeface(custom_regular);
                viewHolder.linear=(LinearLayout) view.findViewById(R.id.linear);

                convertView = view;
                convertView.setTag(viewHolder);
            }
            viewHolder = (ViewHolder) convertView.getTag();
//            System.out.println("n: "+ bbplans.get(position).   );
            viewHolder.tx_price.setText("RS." + allPlans.get(position).getPlanValue());
            viewHolder.tx_validity.setText(allPlans.get(position)
                    .getPlanValidity());
            viewHolder.tx_plansdetails.setText(allPlans.get(position)
                    .getPlansDetails());
            Log.v("TAG_TALKTIME", "" +allPlans.get(position)
                    .getPlanTalktime());
            viewHolder.tx_talktime.setText(allPlans.get(position)
                    .getPlanTalktime());
            viewHolder.linear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    m_editor.putString("amount", allPlans.get(position).getPlanValue());
                    m_editor.commit();
                    getActivity().finish();
                }
            });

            return convertView;
        }

    }

    class ViewHolder {
        TextView tx_price, tx_talktime, tx_validity, tx_plansdetails;
        LinearLayout linear;

    }

}

BrowsePlan.java:

public class BrowsePlan {

    @Expose
    private String PlanType;
    @Expose
    private String PlanValidity;

    public String getPlanTalktime() {
        return PlanTalktime;
    }

    public void setPlanTalktime(String planTalktime) {
        PlanTalktime = planTalktime;
    }

    @Expose
    private String PlanTalktime;
    @Expose
    private String PlansDetails;
    @Expose
    private String RCType;

    public String getPlanValue() {
        return PlanValue;
    }

    public void setPlanValue(String planValue) {
        PlanValue = planValue;
    }

    public String getSortOrder() {
        return SortOrder;
    }

    public void setSortOrder(String sortOrder) {
        SortOrder = sortOrder;
    }

    public String getRCType() {
        return RCType;
    }

    public void setRCType(String RCType) {
        this.RCType = RCType;
    }

    public String getPlansDetails() {
        return PlansDetails;
    }

    public void setPlansDetails(String plansDetails) {
        PlansDetails = plansDetails;
    }



    public String getPlanValidity() {
        return PlanValidity;
    }

    public void setPlanValidity(String planValidity) {
        PlanValidity = planValidity;
    }

    public String getPlanType() {
        return PlanType;
    }

    public void setPlanType(String planType) {
        PlanType = planType;
    }

    @Expose
    private String PlanValue;
    @Expose
    private String SortOrder;



}

executeBrowsePlans();是调用web服务的方法。

当适配器刷新时,焦点中的 view/fragment 可能不会更新。 试试这个:

int currentPstn = lv_browseplans.getCurrentItem();

lv_browseplans.setAdapter(browsePlansAdapter);

lv_browseplans.setCurrentItem(currentPstn);

刚刚更改为 FragmentStatePagerAdapter 而不是 FragmentPagerAdapter SectionsPagerAdapter class

现在正在运行。