刷页时从expandablelist视图中丢失数据

时间:2015-04-08 11:58:23

标签: java fragmentpageradapter

我在viewpager中使用了一个可扩展的列表视图。每个页面都有expandablelistview。单击时,它将显示子视图。每个子视图都有两个按钮和一个textview。按钮用于设置值到textview,例如。递增/递减。我现在面临的问题是,在刷页面时,值会随着textview的所有子视图设置为0(零)而改变。我尝试了下面的代码,但在此之后没有调用getChildView()并且它也没有扩展我的组。

OrderActivity.java

 public class OrderActivity extends FragmentActivity{

    private SlidingTabLayout mSlidingTabLayout;
    private ViewPager mViewPager;
    //private ExpandableListAdapter mAdapter; // added new
    private SamplePagerAdapter myAdapter;

    List<Fragment> myFragments;
    List<String> catList = AppConstants.CATEGORY_LIST;

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

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setDisplayShowHomeEnabled(true);

        this.myAdapter = new SamplePagerAdapter();
        mViewPager = (ViewPager)findViewById(R.id.viewpager);
        mViewPager.setAdapter(this.myAdapter);

        mSlidingTabLayout = (SlidingTabLayout)findViewById(R.id.sliding_tabs);
        mSlidingTabLayout.setViewPager(mViewPager);

        final ImageButton cartImgBtn = (ImageButton)findViewById(R.id.imgBtnCart);
        TextView totalCntItem = (TextView)findViewById(R.id.tvCartItemCount);


    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    public class SamplePagerAdapter extends FragmentPagerAdapter {

        Fragment fragment;

        public SamplePagerAdapter() {
            super(getSupportFragmentManager());
        }

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

        @Override
        public Fragment getItem(int position) {
            switch(position){
                case 0: fragment = new BeveragesFragment();
                    return fragment;
                case 1: fragment = new LightFoodFragment();
                    return  fragment;
                case 2: fragment = new SoftDrinksFragment();
                    return fragment;
                case 3: fragment = new FastFoodFragment();
                    return fragment;
                case 4:
                case 5:
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                case 11:
                case 12:
                case 13: fragment = new BeveragesFragment();
                    return fragment;
                default:
                    return null;
            }
        }


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

        @Override
        public CharSequence getPageTitle(int position) {
            return catList.get(position);
        }


    }
    }

BeverageFragment.java

public class BeveragesFragment extends Fragment{
//public static int totalCounter=0;

//ItemDetails myCartItem;
//ArrayList<ItemDetails> cartItems = new ArrayList<ItemDetails>();

//ExpandableListAdapter beverageAdapter;
ExpandableListView exListCategory;
public BeveragesFragment(){

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if(isVisibleToUser){
        if (ConnectionDetector.isInternetAvailable(getActivity())) {
            new CategoryJSONAsyncTask().execute("http://112.145.152.25/..../GetCateenOrderCategoryItemListDetail?CategoryID=1");

        } else {
            Utility.buildDialog(getActivity()).show();
        }
    }
}

@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
    // Create the view from XML layout.
    final View view = inflater.inflate(R.layout.fragment_beverages, null);
    // Perform additional configuration on layout components here.
    TextView txt1 = (TextView) view.findViewById(R.id.textView);
    txt1.setText("HIIIIIIIIIIIIIIIIIIIII");

    exListCategory = (ExpandableListView) view.findViewById(R.id.myExpandableListView);
    exListCategory.setDividerHeight(2);



    return view;

}


public class CategoryJSONAsyncTask  extends AsyncTask<String,Void,String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        String result = "";
        try {
            HttpGet httpGet = new HttpGet(params[0]);
            httpGet.setHeader("Authorization","BASIC"+" "+ AppConstants.KEY);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httpGet);

            int status = response.getStatusLine().getStatusCode();

            if (status == 200) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);

                return result;
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        ArrayList<CategoryParentItemList> listParent = fetchResponse(result.replace("\n","").trim());

        CategoryItemListAdapter adapter = new CategoryItemListAdapter(BeveragesFragment.this.getActivity(),listParent);
        exListCategory.setAdapter(adapter);
        adapter.notifyDataSetChanged();


        // here following line of code which not worked
        ///  totalCntItem.setText(String.format("%d",CategoryItemListAdapter.getTotalCounter()));
    }
}

public ArrayList<CategoryParentItemList> fetchResponse(String result)
{
    ArrayList<CategoryParentItemList> listParent = new ArrayList<>();
    if (!result.equals(""))
    {
        try
        {
            JSONObject jsono = new JSONObject(result);
            JSONArray jarray = jsono.getJSONArray("SBL");

            CategoryParentItemList parent;

            for (int i = 0; i < jarray.length(); i++)
            {
                ArrayList<CategoryChildListItem> childrens = new ArrayList<>();
                childrens.clear();
                CategoryChildListItem child;

                JSONObject object = jarray.getJSONObject(i);
                System.out.println("SCI: " + object.getInt("SubCategoryID"));
                System.out.println("SCN: " + object.getString("SubCategoryName"));

                JSONArray subItemArray = object.getJSONArray("SubCategoryItemList");

                if (subItemArray.length() > 0)
                {
                    for (int j = 0; j < subItemArray.length(); j++)
                    {
                        JSONObject subItemObject = subItemArray.getJSONObject(j);
                        String strItemName = subItemObject.getString("ItemName");
                        String strDefaultPrice = subItemObject.getString("DefaultPrice");

                        child = new CategoryChildListItem(strItemName, strDefaultPrice);
                        childrens.add(child);

                        Log.i("strItemName", strItemName);
                        Log.i("strDefaultPrice", strDefaultPrice);
                    }
                    parent = new CategoryParentItemList(object.getString("SubCategoryName"),childrens);
                    listParent.add(parent);
                }
            }
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
    }
    return listParent;
}
}

CategoryItemListAdapter.java

public class CategoryItemListAdapter extends BaseExpandableListAdapter{
private Context context;
public static int totalCounter=0;


ItemDetails myCartItem;
ArrayList<ItemDetails> cartItems = new ArrayList<ItemDetails>();

private ArrayList<CategoryParentItemList> listParent;

static class ViewHolderGroup {
    public TextView lblSubCategoryName;
}

static class ViewHolderChild {
    public TextView lblItemName;
    public TextView lblDefualtPrice;
    public TextView lblQty;
    public ImageButton imgPlus;
    public ImageButton imgMinus;
}


public CategoryItemListAdapter(Context context, ArrayList<CategoryParentItemList> listParent) {
    super();
    this.context = context;
    this.listParent = listParent;
    //cartItems = AppConstants.CART_LIST;
}

@Override
public int getGroupCount() {

    return listParent.size();
}

@Override
public int getChildrenCount(int groupPosition) {
    ArrayList<CategoryChildListItem> ch = listParent.get(groupPosition).getChildList();
    return ch.size();
}

@Override
public Object getGroup(int groupPosition) {

    return listParent.get(groupPosition);
}

@Override
public Object getChild(int groupPosition, int childPosition) {
    ArrayList<CategoryChildListItem> ch = listParent.get(groupPosition).getChildList();
    return ch.get(childPosition);
}

@Override
public long getGroupId(int groupPosition) {

    return groupPosition;
}

@Override
public long getChildId(int groupPosition, int childPosition) {

    return childPosition;
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
    //CategoryParentItemList parentItem = (CategoryParentItemList)listParent.get(groupPosition);
    CategoryParentItemList parentItem = (CategoryParentItemList) getGroup(groupPosition);
    ViewHolderGroup holderGroup;

    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.group_header, null);
        holderGroup = new ViewHolderGroup();
        holderGroup.lblSubCategoryName = (TextView) convertView.findViewById(R.id.tvItemName);
        convertView.setTag(holderGroup);
    } else {
        holderGroup = (ViewHolderGroup) convertView.getTag();
    }

    holderGroup.lblSubCategoryName.setText(parentItem.getSubCategoryName());
    return convertView;
}

@Override
public View getChildView(int groupPosition,int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
    //final CategoryParentItemList parentItem = (CategoryParentItemList) listParent.get(groupPosition);
    //final CategoryChildListItem childItem = (CategoryChildListItem) parentItem.getChildList().get(childPosition);
    CategoryChildListItem childItem = (CategoryChildListItem) getChild(groupPosition, childPosition);

    ViewHolderChild holder;


    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.child_row, null);

        holder = new ViewHolderChild();

        holder.lblItemName = (TextView) convertView.findViewById(R.id.tvSubItemName);
        holder.lblDefualtPrice = (TextView) convertView.findViewById(R.id.tvrRupees);
        holder.lblQty = (TextView) convertView.findViewById(R.id.tvQty);
        holder.imgPlus = (ImageButton) convertView.findViewById(R.id.imageButtonPlus);
        holder.imgMinus = (ImageButton) convertView.findViewById(R.id.imageButtonMinus);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolderChild) convertView.getTag();

    }

    holder.lblItemName.setText(childItem.getSubItemName());
    holder.lblDefualtPrice.setText(childItem.getDefaultPrice());

    int tmpCount = Integer.parseInt(holder.lblQty.getText().toString());
    holder.imgPlus.setOnClickListener(new ClickUpdateListener(childItem,holder, tmpCount));
    holder.imgMinus.setOnClickListener(new ClickUpdateListener(childItem, holder, tmpCount));

    return convertView;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}

@Override
public boolean areAllItemsEnabled() {
    return true;
}

public static int getTotalCounter() {
    return totalCounter;
}

private class ClickUpdateListener implements View.OnClickListener {

    ViewHolderChild holder;
    public CategoryChildListItem childItem;
    //String itemName=null;
    //int qty;
    //String price;

    int counter = 0;
    String  counterMin;

    public ClickUpdateListener(CategoryChildListItem childItem,ViewHolderChild holder, int cnt) {
        this.childItem = childItem;
        this.holder = holder;
        this.counter = cnt;
    }


    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.imageButtonPlus) {
            counter = counter + 1;
            totalCounter+=1;
            System.out.println(childItem.getSubItemName()+" : "+childItem.getDefaultPrice() + ": C+ :" + counter);
            //here qty increment click on plus button
            holder.lblQty.setText(String.format("%d",counter));

            notifyDataSetChanged();


        }
        if(v.getId() == R.id.imageButtonMinus){
            counterMin = (String) holder.lblQty.getText();
            counter = Integer.parseInt(counterMin.toString().trim());
            counterMin = null;
            if(counter > 0) {
                counter = counter - 1;
                totalCounter-=1;
                System.out.println(childItem.getSubItemName()+" : "+childItem.getDefaultPrice() + ": C- :" + counter);
                //here qty decrement click on minus button
                holder.lblQty.setText(String.format("%d", counter));
                notifyDataSetChanged();
            }else{
                Toast.makeText(context,"Qty Zero",Toast.LENGTH_SHORT).show();
            }
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

类似的东西:

public static int getTotalCounter() {
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplication() );
     return prefs.getInt( "count", 0 );
}

private class ClickUpdateListener implements View.OnClickListener {

   @Override
   public void onClick(View v) {
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplication() );
     int oldCount = prefs.getInt( "count", 0 );
     prefs.edit().put( "count", oldCount + 1 ).commit();
   }
}