如何处理Android中的“立即购买”按钮?

时间:2017-01-17 12:51:43

标签: android magento

我正在开发一个Android电子商务应用程序,其中有两个不同的按钮。第一个是添加到购物车按钮,另一个是立即购买按钮。

当我点击添加到购物车按钮时,它会成功将项目放入购物车中,点击购物车按钮后,应用程序将进入购物车活动。我做了同样的现在购买,但问题是如何更新我的购物车并单击一下转到购物车活动?

ProductDescription.java:

package com.www.prashant;

import android.app.ProgressDialog;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.slider.library.SliderLayout;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;

public class ProductDescription extends Fragment {

    View V;
    int position;
    ImageView product_image;
    TextView product_desc;
    public TextView price;
    public TextView specialPrice;
    TextView product_name;
    ImageLoader image;
    SliderLayout product_images;
    Button sharbtn;
    public TextView txt_qty;
    public Button btn_plus;
    public Button btn_buy;
    ProgressDialog pdialog;
    public int sum=0;
    public int remove=0;
    String cartMessage;
    String cartMessage1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
        Constants.lastDetails = true;
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.product_details, container, false);

        //Set Navigation mode as Statndard
        ((MainActivity)getActivity()).getSupportActionBar().setNavigationMode(((MainActivity) getActivity()).getSupportActionBar().NAVIGATION_MODE_STANDARD);

        V=v;
        //get Product Position
        position = Constants.product_position;

        //Initialize ids
        product_image=(ImageView) V.findViewById(R.id.product_image);
        product_desc=(TextView) V.findViewById(R.id.textProductDescription);
        price=(TextView) V.findViewById(R.id.text1);
        specialPrice = (TextView) V.findViewById(R.id.textSpecialPrice);
        product_name=(TextView) V.findViewById(R.id.textProductName);
        //sharbtn=(Button)V.findViewById(R.id.sharbtn);
        image=new ImageLoader(getActivity());
        image.DisplayImage(Constants.Product_image.get(position), product_image);

        product_name.setText(Constants.Product_name.get(position));
        product_desc.setText(Constants.Product_desc.get(position));
       // product_adesc.setText(Constants.Product_adesc.get(position));
        if(Constants.Product_specialPrice.get(position) < Constants.Product_price.get(position)
                && Constants.Product_specialPrice.get(position)!=0){
            price.setText(String.format("%.2f",Constants.Product_price.get(position)));
            price.setPaintFlags(price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            specialPrice.setText(String.format("%.2f",Constants.Product_specialPrice.get(position)));
        }
        else {
            price.setText(String.format("%.2f",Constants.Product_price.get(position)));
            specialPrice.setText(null);
        }

        btn_plus = (Button) V.findViewById(R.id.btn_plus);
        btn_buy = (Button) V.findViewById(R.id.btn_buy);
       // btn_minus = (ImageButton) V.findViewById(R.id.btn_minus);
        txt_qty = (TextView) V.findViewById(R.id.txt_qty);

        txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));

        **/* Button Click Listener for Add Qty*/**
        btn_plus.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Constants.Product_pos=position;
                remove=0;
                sum = Integer.parseInt(txt_qty.getText().toString())+1;
                Constants.Product_qty.set(position, sum);
                cartMessage1="Adding product to cart...";
                cartMessage="Product was added successfully";
                new updateCart().execute();
            }
        });

         **/* Button Click Listener for Buy Qty*/**

        btn_buy.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Constants.Product_pos=position;
                remove=0;
                sum = Integer.parseInt(txt_qty.getText().toString())+1;
                Constants.Product_qty.set(position, sum);
                cartMessage1="Adding product to cart...";
                cartMessage="Product was added successfully";
                new updateCart().execute();

            }




        });


        product_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ImageFragment imageFrag=new ImageFragment();
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,imageFrag,null).addToBackStack(null).commit();
                getActivity().setTitle("Images");
            }
        });

        return v;
    }




    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        //((MainActivity)getActivity()).resetActionBar(true, DrawerLayout.LOCK_MODE_LOCKED_OPEN);
        super.onActivityCreated(savedInstanceState);

    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            ((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            ((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
            MainActivity.getInstance().CallFragment(Constants.position);
        }
        return true;
    }



    //Add product to cart task
    public class updateCart extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            if (pdialog==null){
                pdialog=new ProgressDialog(getActivity());
                pdialog.setMessage(cartMessage1);
                pdialog.setCanceledOnTouchOutside(false);
                pdialog.setCancelable(false);
                pdialog.show();

            }
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            // parse json data from server in background

               parseJSONDataAddProductToCart();

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub

            if (pdialog.isShowing()){
                pdialog.dismiss();
                pdialog=null;
            }

            Toast.makeText(getActivity(), cartMessage, Toast.LENGTH_LONG).show();
            //Update Notification Count in action bar icon
            //Constants.cart_count += 1;
            //txt_qty.setText(String.valueOf(sum));
            MainActivity.getInstance().updateHotCount(Constants.ProductCart_Id.size());
            txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));
            // if internet connection and data available show data on list
            // otherwise, show alert text

        }
    }

    //Remove product from cart
    public class removeCartProduct extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            if (pdialog==null){
                pdialog=new ProgressDialog(getActivity());
                pdialog.setMessage(cartMessage1);
                pdialog.setCanceledOnTouchOutside(false);
                pdialog.setCancelable(false);
                pdialog.show();

            }
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            // parse json data from server in background

            parseJSONDataAddProductToCart();

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub

            if (pdialog.isShowing()){
                pdialog.dismiss();
                pdialog=null;
            }

            Toast.makeText(getActivity(), cartMessage,Toast.LENGTH_LONG).show();
            //Update Notification Count in action bar icon
            //Constants.cart_count -= 1;
            //txt_qty.setText(String.valueOf(sum));
            MainActivity.getInstance().updateHotCount(Constants.ProductCart_Id.size());
            txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));
            // if internet connection and data available show data on list
            // otherwise, show alert text

        }
    }

    public void parseJSONDataAddProductToCart(){

        try {

            SoapObject item = new SoapObject(Constants.NAMESPACE, "shoppingCartProductEntity");
            SoapObject request;
            int qty;
            if(remove==0){
                request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductAdd");
                qty=1;

            }else{
                qty= Constants.Product_qty.get(Constants.Product_pos);
                if(qty==0){
                    request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductRemove");
                }else{

                    request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductUpdate");
                }
            }

            // add paramaters and values
            request.addProperty("sessionId", Constants.sessionId);
            PropertyInfo pinfo = new PropertyInfo();
            pinfo.setName("product_id");
            pinfo.setValue(Constants.Product_ID.get(Constants.Product_pos));
            pinfo.setType(String.class);
            item.addProperty(pinfo);

            pinfo = new PropertyInfo();
            pinfo.setName("qty");
            pinfo.setValue(qty);
            pinfo.setType(Double.class);
            item.addProperty(pinfo);

            SoapObject EntityArray = new SoapObject(Constants.NAMESPACE, "shoppingCartProductEntityArray");
            EntityArray.addProperty("products", item);
            request.addProperty("quoteId", Constants.cartId);
            request.addProperty("products",EntityArray);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.dotNet = true;
            envelope.setOutputSoapObject(request);

            //Web method call
            HttpTransportSE androidHttpTransport = new HttpTransportSE(Constants.URL);
            androidHttpTransport.debug = true;
            androidHttpTransport.call("", envelope);
            //get the response
            Object result = envelope.getResponse();

            Constants.CartaddStatus=result.toString();
            if(Constants.CartaddStatus == "true"){
                if (Constants.ProductCart_Id.isEmpty()){
                    Constants.cartArrayPos=0;
                }
                if (!Constants.ProductCart_Id.contains(Constants.Product_ID.get(Constants.Product_pos))) {

                    Constants.ProductCart_Id.add(Constants.cartArrayPos,Constants.Product_ID.get(Constants.Product_pos));
                    Constants.ProductCart_Img.add(Constants.cartArrayPos,Constants.Product_image.get(Constants.Product_pos));
                    Constants.ProductCart_Price.add(Constants.cartArrayPos, Constants.Product_price.get(Constants.Product_pos));
                    Constants.cartArrayPos+=1;
                }
                if (qty==0){
                    Constants.ProductCart_Id.remove(Constants.Product_pos);
                    Constants.ProductCart_Img.remove(Constants.Product_pos);
                    Constants.ProductCart_Price.remove(Constants.Product_pos);
                    Constants.cartArrayPos-=1;

                }
            }


        }  catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
    }

}

ActivityCart:

package com.www.prashant;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;

/**
 * Created by Prashant on 10/16/2016.
 */
public class ActivityCart extends Fragment {
    int run;
    ProgressDialog pdialog;
    View v;
    GridView list2;
    CartImageLoadAdapter adapter;
    public static ActivityCart sActivityCart;
    public Double TotalPrice= 0.00;
    TextView btn_place_order;
    TextView btn_place;
    Button btn_place_ord;
    static String TotalProductCartPrice;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.cart, container, false);

        sActivityCart = this;

        ((MainActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(true);
        ((MainActivity)getActivity()).getSupportActionBar().setNavigationMode(((MainActivity) getActivity()).getSupportActionBar().NAVIGATION_MODE_STANDARD);

        list2=(GridView)v.findViewById(R.id.cartlist);
        //list2.setBackgroundColor(Color.BLACK);
        //list2.setVerticalSpacing(1);
      //  list2.setHorizontalSpacing(1);
        clearData();
        btn_place_order = (TextView) v.findViewById(R.id.btn_place_order);
       // btn_place = (TextView) v.findViewById(R.id.btn_place);
        btn_place_ord = (Button) v.findViewById(R.id.btn_place_ord);
        btn_place_ord.setOnClickListener(listener);

        return v;
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Constants.lastDetails = false;
        ((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null);
        ((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);

        Constants.cartEntry=1;
        new getDataTask().execute();


    }

    void clearData(){
        Constants.Product_ID.clear();
        Constants.Product_name.clear();
        Constants.Product_price.clear();
        Constants.Product_image.clear();
        Constants.Product_qty.clear();
        Constants.Product_specialPrice.clear();
        Constants.Product_desc.clear();
        //Constants.Product_adesc.clear();
    }

    @Override
    public void onDestroy()
    {
        // Remove adapter refference from list
        if (run==1) {
            list2.setAdapter(null);
            //Refresh cache directory downloaded images
            adapter.imageLoader.clearCache();
            adapter.notifyDataSetChanged();
        }
        super.onDestroy();
    }

    //Click Listner for place order button
    public View.OnClickListener listener=new View.OnClickListener(){
        @Override
        public void onClick(View arg0) {

            if(run == 1) {

                // Call Login Function
                if(Constants.Customer_FirstName.equals(""))
                {
                    CartLogin CartLogin=new CartLogin();
                    getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,CartLogin,null).addToBackStack(null).commit();
                    getActivity().setTitle("Login");
                }
                else {
                    // Call Shipping Information Function
                    ActivityCustomerAddress CustomerAddress=new ActivityCustomerAddress();
                    getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,CustomerAddress,null).addToBackStack(null).commit();
                    getActivity().setTitle("Shipping");
                }
            }
            else
                Toast.makeText(getActivity(),"Cart is Empty",Toast.LENGTH_LONG).show();

        }
    };




    // Image urls used in LazyImageLoadAdapter.java file

    public class getDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (pdialog==null){
                pdialog=new ProgressDialog(getActivity());
                pdialog.setMessage("Loading...");
                pdialog.setCanceledOnTouchOutside(getRetainInstance());
                pdialog.setCancelable(false);
                pdialog.show();
            }
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            // parse json data from server in background

            if (!Constants.ProductCart_Id.isEmpty()){
                parseJSONData();
                run=1;
            }else{
                run=0;
            }

            //Get Product Prices
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            // Create custom adapter for listview
            if (run==1) {
                String[] images = new String[Constants.Product_image.size()];
                images = Constants.Product_image.toArray(images);
                adapter = new CartImageLoadAdapter(getActivity(), images);

                //Set adapter to listview
                list2.setAdapter(adapter);

                if (pdialog.isShowing()) {
                    pdialog.dismiss();
                    pdialog = null;
                }
            }else{

                if (pdialog.isShowing()) {
                    pdialog.dismiss();
                    pdialog = null;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("Cart is Empty").setMessage("Start Shopping now !!").create().show();
                run=0;
            }
            // if internet connection and data available show data on list
            // otherwise, show alert text
           // btn_place_order.setText(String.format("Total: %.2f   Place Order", TotalPrice));
            btn_place_order.setText(String.format("%.2f  ", TotalPrice));
            TotalProductCartPrice= btn_place_order.getText().toString();

        }
    }

    // method to parse json data from server
    public void parseJSONData(){

        HttpClient Client = new DefaultHttpClient();
        // Create URL string
        String URL = "http://prashant.com/customApi/cartDetails.php?cartId="+Constants.cartId;
        //Log.i("httpget", URL);
        JSONParser parser =new JSONParser();
        try
        {
            String SetServerString = "";

            // Create Request to server and get response

            HttpGet httpget = new HttpGet(URL);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            SetServerString = Client.execute(httpget, responseHandler);
            Constants.Login=SetServerString;
            JSONArray array=new JSONArray(SetServerString);

            for (int i = 0; i < array.length(); i++) {
                JSONObject obj=array.getJSONObject(i);
                Constants.Product_ID.add(Long.parseLong(obj.getString("productId")));
                Constants.Product_name.add(obj.getString("name"));
                Double price= Double.valueOf(obj.getString("price"));
                int Qty= Integer.parseInt(obj.getString("qty"));
                Constants.Product_price.add(price*Qty);
                Constants.Product_image.add(obj.getString("imageurl"));
                Constants.Product_qty.add(Integer.valueOf(obj.getString("qty")));
                Constants.Product_specialPrice.add((Double.valueOf(obj.getString("spprice")))*Qty);

                // Total Sum of Cart Item price
                TotalPrice += Double.valueOf(Double.valueOf(obj.getString("spprice"))*Qty);

            }

            // Show response on activity
        }
        catch(Exception ex)
        {

        }
    }

    public static ActivityCart getInstance() {
        return sActivityCart;
    }

    public void SyncCart(){
        // Call Shipping Information Function
        ActivityCart SyncCart=new ActivityCart();
        getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,SyncCart,null).addToBackStack(null).commit();
        getActivity().setTitle("Cart");
    }

}

0 个答案:

没有答案