如何在单击内部按钮时更新视图寻呼机

时间:2016-05-12 06:43:02

标签: android listview android-viewpager

我正在尝试更新listview项目。 Listview位于视图寻呼机中。我有两个按钮首先是蔬菜,第二个是非蔬菜,当我点击蔬菜蔬菜项目显示和点击非蔬菜非蔬菜项目显示。但它不起作用。

HomeFregment: -

public class HomeFragment extends Fragment {
    JSONArray data = new JSONArray();
    private View parentView;
    private ResideMenu resideMenu;
    private final Handler handler = new Handler();
    private PagerSlidingTabStrip tabs;
    private ViewPager pager;
    //private MyPagerAdapter adapter;
    private Drawable oldBackground = null;
    private ProgressDialog dialog;
    private SharedPreferences loginPreferences;
    private int currentColor = Color.parseColor("#029fa6");
    private ConnectionDetector connectionDetector;
    Boolean nonveg = false;
    String type = "both";

    CustomPagerAdapter adapterCustom;
    JSONArray jsonArray = new JSONArray();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        parentView = inflater.inflate(R.layout.activity_main, container, false);
        setUpViews();
        tabs = (PagerSlidingTabStrip)parentView. findViewById(R.id.tabs);
       // tabs.setTabBackground(Color.parseColor("#e34037"));
       // tabs.setBackgroundColor(Color.parseColor("#e34037"));
        pager = (ViewPager)parentView. findViewById(R.id.pager);
        resideMenu = new ResideMenu(getContext(), R.layout.side_menu, R.layout.home);


        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
              //  Log.d("posscr",position+"");


                if(position >1){
                    //Log.d("scrolled","if");
                   MenuActivity.resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_LEFT);

                }

            }

            @Override
            public void onPageSelected(int position) {
             //   Log.d("position",position+"");
                if(position >1){
                    //Log.d("selected","if");
                    MenuActivity.resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_LEFT);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Log.d("state",state+"");
                if(state !=0){
                    Log.d("stat","if");
                    MenuActivity.resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_LEFT);
                }
            }
        });
        connectionDetector = new ConnectionDetector(getActivity().getApplicationContext());
 //       adapter = new MyPagerAdapter(getActivity().getSupportFragmentManager());
//        pager.setAdapter(new CustomPagerAdapter(getActivity()));
//        final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
//                .getDisplayMetrics());
//        pager.setPageMargin(pageMargin);
//        tabs.setViewPager(pager);
//        changeColor(currentColor);
        dialog = new ProgressDialog(getActivity());
        dialog.setMessage(" Please Wait While Loading...");
        dialog.setCancelable(false);
        loginPreferences = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
        if (connectionDetector.isConnectingToInternet()){
            getCategoryData();
        }else{
            Toast.makeText(getActivity().getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
        }
        return parentView;
    }

    private void setUpViews() {
        MenuActivity parentActivity = (MenuActivity) getActivity();
        resideMenu = parentActivity.getResideMenu();


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case R.id.action_settings:
                QuickContactFragment dialog = new QuickContactFragment();
                dialog.show(getActivity().getSupportFragmentManager(), "QuickContactFragment");
                return true;

        }
        return super.onOptionsItemSelected(item);
    }

    private void changeColor(int newColor) {
        tabs.setIndicatorColor(newColor);
        // change ActionBar color just if an ActionBar is available
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            Drawable colorDrawable = new ColorDrawable(newColor);
            Drawable bottomDrawable = getResources().getDrawable(R.drawable.actionbar_bottom);
            LayerDrawable ld = new LayerDrawable(new Drawable[] { colorDrawable, bottomDrawable });
            if (oldBackground == null) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    ld.setCallback(drawableCallback);
                } else {
                  //  getActivity().getActionBar().setBackgroundDrawable(ld);
                }
            } else {
                TransitionDrawable td = new TransitionDrawable(new Drawable[] { oldBackground, ld });

                // workaround for broken ActionBarContainer drawable handling on
                // pre-API 17 builds
                // https://github.com/android/platform_frameworks_base/commit/a7cc06d82e45918c37429a59b14545c6a57db4e4
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    td.setCallback(drawableCallback);
                } else {
                  //  getActivity().getActionBar().setBackgroundDrawable(td);
                }
                td.startTransition(200);
            }
            oldBackground = ld;
        }
        currentColor = newColor;
    }

    public void clickOnVegCatgory(View v){
        //Toast.makeText(getContext(), "call", Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("currentColor", currentColor);
    }
    private Drawable.Callback drawableCallback = new Drawable.Callback() {
        @Override
        public void invalidateDrawable(Drawable who) {
           getActivity().getActionBar().setBackgroundDrawable(who);
        }

        @Override
        public void scheduleDrawable(Drawable who, Runnable what, long when) {
            handler.postAtTime(what, when);
        }

        @Override
        public void unscheduleDrawable(Drawable who, Runnable what) {
            handler.removeCallbacks(what);
        }
    };
    /*public int getItemPosition(Object object) {
        return POSITION_NONE;
    }*/
    public class MyPagerAdapter extends FragmentPagerAdapter {

        private final String[] TITLES = { "Categories", "Home", "Top Paid", "Top Free", "Top Grossing", "Top New Paid",
                "Top New Free", "Trending" };

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return TITLES[position];
        }

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

        @Override
        public Fragment getItem(int position) {
            return SuperAwesomeCardFragment.newInstance(position);
        }
    }
//    public enum CustomPagerEnum {
//
//        RED("my_profile", R.layout.my_profile),
//        BLUE("register_page", R.layout.register_page),
//        ORANGE("calendar", R.layout.calendar);
//        private String mTitleResId;
//        private int mLayoutResId;
//        CustomPagerEnum(String titleResId, int layoutResId) {
//            mTitleResId = titleResId;
//            mLayoutResId = layoutResId;
//        }
//        public String getTitleResId() {
//            return mTitleResId;
//        }
//        public int getLayoutResId() {
//            return mLayoutResId;
//        }
//
//    }
    public class CustomPagerAdapter extends PagerAdapter {


        private JSONArray CategoryData;
        private Context mContext;
        private HomeLiatAdapter homeLiatAdapter;
       JSONArray mainJson= new JSONArray();

    JSONArray vegArray;
    JSONArray  nonvegArray;


    ListView list;
    JSONObject obj,jsonBothTypeObject;
   /* Button veg_btn;
    Button nonveg_btn;*/

    public CustomPagerAdapter(Context context,JSONArray category_data) {
            mContext = context;
            CategoryData = category_data;

        Log.d("value","call");

        }
        @Override
        public Object instantiateItem(ViewGroup collection,int position) {
            Log.d("postion",position+"");

            //CustomPagerEnum customPagerEnum = CustomPagerEnum.values()[position];

                LayoutInflater inflater = LayoutInflater.from(mContext);
                ViewGroup layout = (ViewGroup) inflater.inflate( R.layout.home_child_layout, collection, false);
                collection.addView(layout);
                final ImageView home_child_image = (ImageView) layout.findViewById(R.id.home_child_image);

                final Button  veg_btn  = (Button)layout.findViewById(R.id.veg_btn);
                final Button nonveg_btn = (Button)layout.findViewById(R.id.nonveg_btn);
                list = (ListView) layout.findViewById(R.id.list);
                veg_btn.setBackgroundColor(Color.parseColor("#ffffff"));
                veg_btn.setTextColor(Color.parseColor("#000000"));
                try {
                    JSONObject obj = CategoryData.getJSONObject(position);
                    JSONObject jsonBothTypeObject = CategoryData.getJSONObject(position).getJSONObject("items");
                    //jsonObject = obj.getJSONObject("items");

//                    Toast.makeText(getActivity(), "test", Toast.LENGTH_SHORT).show();


                    if(!obj.getString("bigimage").equals("")){
                        Picasso.with(getActivity())
                                .load(obj.getString("bigimage"))
                                .error(R.drawable.images)
                                .placeholder(R.drawable.progress_animation)
                                .into(home_child_image);
                    }
                    vegArray   = jsonBothTypeObject.getJSONArray("veg");
                    nonvegArray = jsonBothTypeObject.getJSONArray("nonveg");
                    veg_btn.setContentDescription(position+"");
                    nonveg_btn.setContentDescription(position+"");

                /*veg_btn.setContentDescription(vegArray+"");
                nonveg_btn.setContentDescription(nonvegArray+"");*/
                    if(vegArray.length()==0){
                        veg_btn.setVisibility(View.GONE);
                        nonveg_btn.setVisibility(View.GONE);

                        JSONArray jsonArray = concatArray(vegArray,nonvegArray);
                        list.setAdapter(new HomeLiatAdapter(mContext,jsonArray,type));
                        notifyDataSetChanged();

                    }
                    else if (nonvegArray.length()==0){
                        nonveg_btn.setVisibility(View.GONE);
                        veg_btn.setVisibility(View.GONE);
                        JSONArray jsonArray = concatArray(vegArray,nonvegArray);
                        list.setAdapter(new HomeLiatAdapter(mContext,jsonArray,type));
                        notifyDataSetChanged();


                    }
                    else {
                        type = "veg";
                        //JSONArray jsonArray = concatArray(vegArray,nonvegArray);
                        list.setAdapter(new HomeLiatAdapter(mContext,vegArray,type));
                        notifyDataSetChanged();

                    }

                }catch (Exception e){
                    e.printStackTrace();
                    Log.e("error",e.getMessage());
                }

                veg_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        nonveg_btn.setBackgroundColor(Color.parseColor("#ffffff"));
                        nonveg_btn.setTextColor(Color.parseColor("#cf352d"));
                        veg_btn.setBackgroundColor(Color.parseColor("#cf352d"));
                        veg_btn.setTextColor(Color.parseColor("#ffffff"));
                        try {
                            int pos = Integer.parseInt(v.getContentDescription().toString());
                            Log.d("postion",pos+"");
                            JSONObject jsonBothTypeObject = CategoryData.getJSONObject(pos).getJSONObject("items");
                            JSONArray vegArray   = jsonBothTypeObject.getJSONArray("veg");
                            JSONArray nonvegArray = jsonBothTypeObject.getJSONArray("nonveg");
                            list.setAdapter(new HomeLiatAdapter(mContext,vegArray,"veg"));
                            //notifyDataSetChanged();

                        }
                        catch (JSONException e){
                            Log.d("Error",e.getMessage());
                        }

                        /*type = "veg";
                        notifyDataSetChanged();*/
                    }
                });

                nonveg_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        nonveg_btn.setBackgroundColor(Color.parseColor("#cf352d"));
                        nonveg_btn.setTextColor(Color.parseColor("#ffffff"));
                        veg_btn.setBackgroundColor(Color.parseColor("#ffffff"));
                        veg_btn.setTextColor(Color.parseColor("#cf352d"));

                        // pager.setAdapter(new CustomPagerAdapter(mContext,data));
                        try {
                            int pos = Integer.parseInt(v.getContentDescription().toString());
                            Log.d("postion21",pos+"");
                            JSONObject jsonBothTypeObject = CategoryData.getJSONObject(pos).getJSONObject("items");
                            JSONArray vegArray   = jsonBothTypeObject.getJSONArray("veg");
                            JSONArray nonvegArray = jsonBothTypeObject.getJSONArray("nonveg");
                            list.setAdapter(new HomeLiatAdapter(mContext,nonvegArray,"non"));


                        }
                        catch (JSONException e){
                            Log.d("Error",e.getMessage());
                        }
/*
                    type = "non";
                    notifyDataSetChanged();*/


                    }
                });


                //    Log.d("item",obj.getJSONArray("items")+"");

            /*    if((obj.getJSONArray("items").length())>1){
                    nonveg = true;
                }else
                    nonveg = false;
*/

                return layout;


        }

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

    @Override
        public void destroyItem(ViewGroup collection, int position, Object view) {
            collection.removeView((View) view);
        }

        @Override
        public int getCount() {
            return CategoryData.length();
            //return CustomPagerEnum.values().length;
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
        //CustomPagerEnum customPagerEnum = CustomPagerEnum.values()[position];
            String categoryname = "";
            try {
                JSONObject obj = CategoryData.getJSONObject(position);
                categoryname = obj.getString("categoryname");
                return obj.getString("categoryname");
            }catch (Exception e){
                e.printStackTrace();
            }
            return categoryname;
            //return (customPagerEnum.getTitleResId());
        }
    }

    private void getCategoryData(){
        dialog.show();
        Ion.with(getActivity())
                .load(getResources().getString(R.string.api_main_url) + "category.php")
                .setTimeout(20*1000)
                .asString().setCallback(new FutureCallback<String>() {
            @Override
            public void onCompleted(Exception e, String result) {
                dialog.cancel();
                if (e != null) {
                    e.printStackTrace();
                    DialogsClassTwo(getActivity(), "Connection Timed Out!", "Opps...").show();
                }
                if (result != null) {
                    try {
                        JSONObject mainJson = new JSONObject(result);
                        String status = mainJson.getString("status");
                        String message = mainJson.getString("message");
                        if(status.equals("Success")){
                            //{"data":[{"id":"1","categoryname":"Burgers","bigimage":"http:\/\/192.168.1.7\/burgerfarm\/upload_images\/category_image\/6340_xl.jpg",
                            // "status":"707","sortorder":"1","items":
                            data = mainJson.getJSONArray("data");
                           // adapter = new MyPagerAdapter(getActivity().getSupportFragmentManager());
                            adapterCustom = new CustomPagerAdapter(getActivity(),data);
                            pager.setAdapter(adapterCustom);

                            final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
                            pager.setPageMargin(pageMargin);
                            tabs.setViewPager(pager);
                            changeColor(currentColor);

                        }
                    }catch (Exception ex) {
                        ex.printStackTrace();
                        Log.d("exaption", ex.toString());

                    }
                } else {
                    Log.d("exaption", e.toString());
                }
            }
        });
    }
    public AlertDialog.Builder DialogsClassTwo(Context cxt,String message,String title){
        return  new AlertDialog.Builder(cxt).setTitle(title).setMessage(message).setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogs, int which) {
                // here you can add functions
                if (CheckInternetConection.isInternetConnection(getActivity().getApplicationContext())){
                    getCategoryData();
                }else{
                    //Toast.makeText(getActivity(), "hello", Toast.LENGTH_SHORT).show();
                    InternetDialoge.showDialogFinishActivity(
                            "Internet Connection Failed!", "connection error", getActivity());
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
//        if(data.length()>0){
//            adapter = new MyPagerAdapter(getActivity().getSupportFragmentManager());
//            pager.setAdapter(new CustomPagerAdapter(getActivity(),data));
//            final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
//                    .getDisplayMetrics());
//            pager.setPageMargin(pageMargin);
//            tabs.setViewPager(pager);
//            changeColor(currentColor);
//        }
    }

    private JSONArray concatArray(JSONArray arr1, JSONArray arr2)
            throws JSONException {
        JSONArray result = new JSONArray();
        for (int i = 0; i < arr1.length(); i++) {
            result.put(arr1.get(i));
        }
        for (int i = 0; i < arr2.length(); i++) {
            result.put(arr2.get(i));
        }
        return result;
    }
}

我是android开发的新手请帮助我

这是我的EXM: -

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="#282828"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/home_child_image"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scaleType="fitXY"
        android:src="@drawable/product_banner"/>
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <Button
        android:id="@+id/veg_btn"
        android:layout_weight="1"
        android:text="@string/veg"
        android:background="#cf352d"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/nonveg_btn"
        android:layout_weight="1"
        android:text="@string/nonveg"
        android:background="#cf352d"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>
    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>
</LinearLayout>

以下是我的截图:

[HERE MY SCRRENSHOT

这里是我的适配器类: -

public class HomeLiatAdapter extends BaseAdapter {
    private JSONArray result;
    private Context context;
    private Holder holder;
    private String total;
    private  int int_total;
    private Database database;
    ArrayList<String> hasmap_key = new ArrayList<>();
    //HashMap<String,String[]> hasmapdata = new HashMap<String,String[]>();
    private static LayoutInflater inflater = null;
    Boolean nonveg;
    String type="";

    public HomeLiatAdapter(Context mainActivity,JSONArray CategoryData,String type) {
    //  result = Data;
        context = mainActivity;
        result = new JSONArray();
        result = CategoryData;
        inflater = (LayoutInflater) context.
                getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        database = new Database(context);
        int value = gettotal();
        this.nonveg = nonveg;
        MenuActivity.txt_total_rate.setText("Total "+context.getResources().getString(R.string.rs)+" "+value);

        this.type = type;


    }
    private int gettotal(){
        Cursor cur = database.getData("SELECT SUM(total) FROM cart");
        if(cur.moveToFirst())
        {
            return cur.getInt(0);
        }
        else{
            return  0;
        }
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        // return result.length;
        Log.d("result.length()",""+result.length());
        return result.length();
    }

    @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;
    }
    public class Holder {
       // TextView id_title;
        TextView txt_product_name,txt_quantity;
        ImageView profile_image,txt_minese,txt_pluse;
        LinearLayout ll_vage_nonvage;
        Button btn_rate;//,btn_addon;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        holder = new Holder();
        View rowView;
        if(result.length()>0){
            if(position == (result.length()-1)){
                getTotalRate();
            }
        }
       // MenuActivity.title_bar_right_menu.setText(""+StaticData.hasmapdata.size());
        rowView = inflater.inflate(R.layout.child_home_list, null);
        holder.profile_image = (ImageView) rowView.findViewById(R.id.profile_image);
        //holder.id_title = (TextView) rowView.findViewById(R.id.id_title);
        holder.txt_product_name = (TextView) rowView.findViewById(R.id.txt_product_name);
        holder.txt_quantity = (TextView) rowView.findViewById(R.id.txt_quantity_increaae_item);
        holder.txt_minese = (ImageView) rowView.findViewById(R.id.txt_minese);
        holder.txt_pluse = (ImageView) rowView.findViewById(R.id.txt_pluse);
        holder.btn_rate = (Button) rowView.findViewById(R.id.btn_rate);

       // holder.ll_vage_nonvage = (LinearLayout) rowView.findViewById(R.id.ll_vage_nonvage);
        //holder.btn_addon = (Button) rowView.findViewById(R.id.btn_addon);

        holder.txt_pluse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    JSONObject obj = result.getJSONObject(position);

                    SQLiteDatabase tm = new Database(context).getWritableDatabase();
                    int id = Integer.parseInt(obj.getString("id"));
                    Cursor cursor = database.getData("select * from cart where products_id='" + id + "'");
                    if(cursor.moveToFirst()){
                        int qty = cursor.getInt( cursor.getColumnIndex("qty"));
                        String strSQL = "UPDATE cart SET qty = qty+1 WHERE products_id = "+ id;
                        tm.execSQL(strSQL);
                        Double price = Double.parseDouble(obj.getString("productprice"));
                        int total = (qty+1)*price.intValue();
                        //"UPDATE message SET MSG_TYPE = '"+ path +"' WHERE TO_ID = "+ chatMessageObj.getMSGId();
                        String strSTQ1 = "UPDATE cart SET total = '"+total +"' WHERE products_id = "+ id;
                        tm.execSQL(strSTQ1);

                        holder.txt_quantity.setText((qty+1)+"");

                    }
                    else {
                        String name = obj.getString("productname");
                        String price = obj.getString("productprice");
                        Double pri = Double.parseDouble(price);


                        database.storeInCart(id,name,pri.intValue(),1,(1*pri.intValue()));

                        holder.txt_quantity.setText(1+"");
  //                      holder.txt_quantity.setText("plus else");


                    }
                 /*   String text =  holder.txt_quantity.getText().toString();
                    int count = Integer.parseInt(text) + 1;
                    holder.txt_quantity.setText(""+count);
                    String[] newdata = new String[2];

                    if(StaticData.hasmapdata.containsKey(obj.getString("id"))){
                        String[] data = StaticData.hasmapdata.get(obj.getString("id"));
                        newdata[0] = data[0];
                        int counter =  Integer.parseInt(data[1] )+ 1;
                        newdata[1] = ""+counter;
                        StaticData.hasmapdata.put(obj.getString("id"), newdata);
                    }else{
                        newdata[0] = obj.toString();
                        newdata[1] = ""+count;
                        StaticData.hasmapdata.put(obj.getString("id"),newdata);
                    }*/
                    notifyDataSetChanged();
                }catch (Exception e){
                    e.printStackTrace();
                }

                Cursor cursor1 =  database.getData("SELECT * FROM cart");
                int count = cursor1.getCount();

                int value = gettotal();
                MenuActivity.txt_total_rate.setText("Total "+context.getResources().getString(R.string.rs)+" "+value);
            //    Log.d("count",count+""+"hello");

                MenuActivity.title_bar_right_menu.setText(count+"");
            }
        });

        holder.txt_minese.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //  String text =  holder.txt_quantity.getText().toString();
                try {
                    JSONObject obj = result.getJSONObject(position);
                    int id = Integer.parseInt(obj.getString("id"));
                    SQLiteDatabase tm = new Database(context).getWritableDatabase();
                    Cursor cursor = database.getData("select * from cart where products_id='" + id + "'");
                    if(cursor.moveToFirst()){
                        int qty = cursor.getInt( cursor.getColumnIndex("qty"));
                        Log.d("qty",qty+"");
                        if(qty==1){
                            String strSQL1 = "DELETE FROM cart where products_id='"+id+"'";
                            tm.execSQL(strSQL1);

                            holder.txt_quantity.setText(0+"");
//                            holder.txt_quantity.setText("minus");

                        }
                        else {
                            String strSQL = "UPDATE cart SET qty = qty-1 WHERE products_id = "+ id;
                            tm.execSQL(strSQL);

                            Double price = Double.parseDouble(obj.getString("productprice"));
                            int total = (qty-1)*price.intValue();
                            //"UPDATE message SET MSG_TYPE = '"+ path +"' WHERE TO_ID = "+ chatMessageObj.getMSGId();
                            String strSTQ1 = "UPDATE cart SET total = '"+total +"' WHERE products_id = "+ id;
                            tm.execSQL(strSTQ1);


                            holder.txt_quantity.setText((qty-1)+"");
                      //      holder.txt_quantity.setText("minus else");
//
                        }
                    }

                        notifyDataSetChanged();
                    }catch (Exception e){
                        e.printStackTrace();
                    Log.e("error",e.getMessage());
                    }
                Cursor cursor1 =  database.getData("SELECT * FROM cart");
                int count = cursor1.getCount();

                int value = gettotal();
                MenuActivity.txt_total_rate.setText("Total "+context.getResources().getString(R.string.rs)+" "+value);
                //    Log.d("count",count+""+"hello");

                MenuActivity.title_bar_right_menu.setText(count+"");

               // }
            }
        });
        try {
            JSONObject obj = result.getJSONObject(position);
            Log.d("obj",""+result.length());

            if(type.equalsIgnoreCase("veg")){
                if(obj.getString("producttype").equals("1")){
                    int id = Integer.parseInt(obj.getString("id"));
                    Cursor cursor = database.getData("select * from cart where products_id='" + id + "'");
                    if(cursor.moveToFirst()){
                        int qty = cursor.getInt( cursor.getColumnIndex("qty"));
                        //   Log.d("qty123",qty+"");
                        holder.txt_quantity.setText(String.valueOf(qty));
                    }
                    String[] data = StaticData.hasmapdata.get(obj.getString("id"));

                    //  }
                    holder.txt_product_name.setText(obj.getString("productname"));
                    holder.btn_rate.setText(context.getResources().getString(R.string.rs)+" "+obj.getString("productprice"));
                    if(!obj.getString("thumbimage").equals("")){
                        Picasso.with(context)
                                .load(obj.getString("thumbimage"))
                                .error(R.drawable.images)
                                .placeholder(R.drawable.progress_animation)
                                .into(holder.profile_image);
                    }
                }
            }
            else if(type.equals("non")){
                if(!obj.getString("producttype").equals("1")){
                    int id = Integer.parseInt(obj.getString("id"));
                    Cursor cursor = database.getData("select * from cart where products_id='" + id + "'");
                    if(cursor.moveToFirst()){
                        int qty = cursor.getInt( cursor.getColumnIndex("qty"));
                        //   Log.d("qty123",qty+"");
                        holder.txt_quantity.setText(String.valueOf(qty));
                    }
                    String[] data = StaticData.hasmapdata.get(obj.getString("id"));

                    //  }
                    holder.txt_product_name.setText(obj.getString("productname"));
                    holder.btn_rate.setText(context.getResources().getString(R.string.rs)+" "+obj.getString("productprice"));
                    if(!obj.getString("thumbimage").equals("")){
                        Picasso.with(context)
                                .load(obj.getString("thumbimage"))
                                .error(R.drawable.images)
                                .placeholder(R.drawable.progress_animation)
                                .into(holder.profile_image);
                    }
                }
            }
            else {
                int id = Integer.parseInt(obj.getString("id"));
                Cursor cursor = database.getData("select * from cart where products_id='" + id + "'");
                if(cursor.moveToFirst()){
                    int qty = cursor.getInt( cursor.getColumnIndex("qty"));
                    //   Log.d("qty123",qty+"");
                    holder.txt_quantity.setText(String.valueOf(qty));
                }
                String[] data = StaticData.hasmapdata.get(obj.getString("id"));

                //  }
                holder.txt_product_name.setText(obj.getString("productname"));
                holder.btn_rate.setText(context.getResources().getString(R.string.rs)+" "+obj.getString("productprice"));
                if(!obj.getString("thumbimage").equals("")){
                    Picasso.with(context)
                            .load(obj.getString("thumbimage"))
                            .error(R.drawable.images)
                            .placeholder(R.drawable.progress_animation)
                            .into(holder.profile_image);
                }
            }


        }catch (Exception e){
            e.printStackTrace();
        }
      //  notifyDataSetChanged();
        return rowView;
    }
    private void getTotalRate(){
        double Subtotal = 0.0;
        Iterator myVeryOwnIterator = StaticData.hasmapdata.keySet().iterator();
        while(myVeryOwnIterator.hasNext()) {
            String key=(String)myVeryOwnIterator.next();
            hasmap_key.add(key);
            String[] value = StaticData.hasmapdata.get(key);
            try {
                JSONObject obj = new JSONObject(value[0]);
                String rate  = obj.getString("productprice");
                Subtotal += Double.parseDouble(rate) * Double.parseDouble(value[1]);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
       // MenuActivity.txt_total_rate.setText("Total Rs "+Subtotal);
    }
}

0 个答案:

没有答案