当前位置: 首页 > 知识库问答 >
问题:

查看寻呼机第一和第二段数据不更新时,数据在Android中改变?

袁晟
2023-03-14

我正在使用视图页(动态)显示来自服务的数据。它工作得很好,但是每当我再次调用服务时,视图分页器中的数据需要刷新并使用新的数据(来自服务)进行更新。

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();


    }

}
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;

    }

}

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服务的方法。

共有1个答案

顾俊哲
2023-03-14

只是在SectionsPagerAdapter类中更改为FragmentStatePagerAdapter而不是FragmentPagerAdapter

它现在起作用了。

 类似资料:
  • 我需要制作一个电子商务应用程序类型的屏幕,具有多个viewpager和recycler视图。 我实现了它,但我的1/2视图寻呼机在回收器视图中可见,一旦我旋转设备,我的第一个视图寻呼机也会消失。 我的活动: 我的视图寻呼机片段: 我的回收器视图的主适配器: 我的视图寻呼机适配器: 我的水平回收器视图适配器: 主要活动布局: 水平滚动布局: 查看寻呼机布局: 根据我的JSON数据,在recycler

  • 所以我试着用可视寻呼机在屏幕间切换。我试着不使用碎片来做这件事,但是我不能让它工作。我在第59行得到一个错误,它是mview pager . setadapter(mCustomPagerAdapter);当我试图设置我的适配器时出现空指针异常。我在这里找到了一个例子。我想我在这个问题上有些力不从心,这是我第一次尝试使用可视寻呼机。 这是我的路由详细信息活动,我试图设置适配器 这是我的自定义页面适

  • 我有两个火花数据集,其中一个列的帐户和键,键列在数组的格式[key1, key2, key3...]和另一个数据集的两个列的帐户和键值是在json.帐户,{key:值,键,值...}。我需要更新第二个数据集中的值,如果键出现在第一个数据集中。 预期产出

  • 我正在做一个计算器应用程序,想要更新历史在第二个片段,但不能找到一个完美的解决方案更新列表视图在第二个片段。我试过很多种解决办法,但没有一种有效。我正在使用ViewPager在计算器和历史片段之间滑动。我厌倦了bundle类,但如果我在ViewPager的第一个片段(CalculatorFragment)的OnCreat方法中使用bundle,它在启动应用程序后会显示空白屏幕&如果我在Equal按

  • UserViewModel: 用户存储库:

  • Hy,我是android开发的新手,我正在尝试在我的自定义对话框片段(扩展了DialogFragment并包含四个按钮)和view Pager中的片段之间建立一个通信。 我的视图分页器适配器扩展了FragmentStatePagerAdapter并包含7个选项卡,但对于每个选项卡,我创建了相同的片段,该片段具有一个recyclerView,但用于列表的数据不同。这个想法是,如果我单击对话框片段中的