Я использую view pager (динамический) для отображения данных из службы. Он работает нормально, но всякий раз, когда я вызывал службу снова, данные в пейджере просмотра должны обновлять и обновлять новыми данными (из службы).
Все фрагменты в представлении pager обновляются новыми данными, но первые два фрагмента просмотра пейджера не обновляются новыми данными, эти два фрагмента (первый и второй) отображаются только с предыдущими данными. пожалуйста, помогите мне.
мой код:
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(); это метод вызова веб-сервиса.