Android Spinner集选择属性不起作用

时间:2020-06-09 15:59:41

标签: android android-spinner

我正在使用android微调器,陷入了一个简单的问题,但尝试了很多却无法解决。 spinner.setselection不起作用。 这是代码。完整的代码不错,但是代码中的问题仅在于edDealerID。我使用包含简单硬编码值的简单字符串Array为其设置了适配器,但是当我选择setselection(1)后,它给了我ArrayIndexOutOfBound错误:length = 1;索引= 1。 请有人帮我。 预先感谢。

package com.example.younastraders.tabsreturn;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;

import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.younastraders.DealersAndProductsInfo;
import com.example.younastraders.GetData;
import com.example.younastraders.GlobalVariables;
import com.example.younastraders.InputFilterMinMax;
import com.example.younastraders.R;
import com.example.younastraders.SendData;
import com.toptoche.searchablespinnerlibrary.SearchableSpinner;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AddReturnFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AddReturnFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";


    int extraCount;
    int maxExtraProducts = 50;
    float orderPrice = 0;
    String bonus = "";
    float discount = 0;
    float finalPrice = 0;
    Button btnSubmitOrder;
    Button btnSaveOrder;
    SearchableSpinner edDealerID;

    SearchableSpinner[] orgProducts;
    EditText[] orgqQuantity;
    Spinner[] orgUnit;

    LinearLayout[] subLayout;
    LinearLayout[] subLayoutDetail1;
    LinearLayout[] subLayoutDetail2;
    SearchableSpinner[] extraProducts;
    SearchableSpinner[] extraBatch;
    SearchableSpinner[] returnReason;
    EditText[] extraQuantity;
    EditText[] extraDiscount;
    Spinner[] extraUnits;
    Button[] extraOpBtn;
    ProgressBar edProgress;
    SendData objSendData;
    Button btnAdd;
    EditText edOrderPrice;
    EditText edCashReturn;

    ArrayAdapter<String> dealerAdapter;
    ArrayAdapter<String> productAdapter;
    ArrayAdapter<String> unitAdapter;
    ArrayAdapter<String> returnAdapter;
    ArrayAdapter<String> batchAdapter[];
    LinearLayout lv;

    public String[] dealersId;
    public String[] dealersName;
    public String[] dealersAddress;
    public String[] productsIds;
    public String[] productsName;
    public float[] productsPrice;

    private ArrayList<ArrayList<String>> batchwiseStock;
    private ArrayList<String> batchProductIds;
    GetData objGetData;
    String[] batchIds;

    String stDate;
    String stTime;

    String send_dealerId;
    String send_productIds = "";
    String send_quantities = "";
    String send_batchno = "";
    String send_return_price = "";
    String send_unit = "";
    String send_return_reason = "";
    String send_cash_return = "";
    float returnTotalPrice = 0.0f;

    Boolean editPrevious = false;
    String editReturnId;
    String editDealerId;
    String editProductId;
    String editBatch;
    String editQuantity;
    String editUnit;
    String editReason;
    String editReturnPrice;
    String editCashReturn;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public AddReturnFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ExploreFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static AddReturnFragment newInstance(String param1, String param2) {
        AddReturnFragment fragment = new AddReturnFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    private int findIndexInArray(String query, String[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].equals(query)) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_add_return, container, false);
        DealersAndProductsInfo objdealandproinfo = new DealersAndProductsInfo(getActivity());
        dealersId = objdealandproinfo.getDealersId();
//        dealersName = objdealandproinfo.getDealersName();
        dealersName = new String[5];
        dealersName[0] = "Dealer 1";
        dealersName[1] = "Dealer 2";
        dealersName[2] = "Dealer 3";
        dealersName[3] = "Dealer 4";
        dealersName[4] = "Dealer 5";
        dealersAddress = objdealandproinfo.getDealersAddress();
        productsIds = objdealandproinfo.getProductsIds();
        productsName = objdealandproinfo.getProductsName();
        productsPrice = objdealandproinfo.getProductsPrice();
        orgProducts = new SearchableSpinner[4];
        orgqQuantity = new EditText[4];
        orgUnit = new Spinner[4];
        edOrderPrice = rootView.findViewById(R.id.edorderprice);
        edCashReturn = rootView.findViewById(R.id.edcashreturn);
        edOrderPrice.setText(String.valueOf(orderPrice));

        objGetData = new GetData(getActivity(), "Batchwise Stock");
        batchwiseStock = objGetData.getBatchwiseStock();
        batchProductIds = objGetData.getBatchProductIds();
        batchAdapter = new ArrayAdapter[batchProductIds.size()];
        batchIds = new String[batchProductIds.size()];
        batchIds = batchProductIds.toArray(batchIds);

        subLayout = new LinearLayout[maxExtraProducts];
        subLayoutDetail1 = new LinearLayout[maxExtraProducts];
        subLayoutDetail2 = new LinearLayout[maxExtraProducts];
        extraProducts = new SearchableSpinner[maxExtraProducts];
        extraBatch = new SearchableSpinner[maxExtraProducts];
        returnReason = new SearchableSpinner[maxExtraProducts];
        extraQuantity = new EditText[maxExtraProducts];
        extraDiscount = new EditText[maxExtraProducts];
        extraUnits = new Spinner[maxExtraProducts];
        extraOpBtn = new Button[maxExtraProducts];

        objSendData = new SendData(getActivity());
        extraCount = 0;
        btnAdd = rootView.findViewById(R.id.button_add);
        edDealerID = rootView.findViewById(R.id.ed_dealerName);
        lv = rootView.findViewById(R.id.linear_layout);

        dealerAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, dealersName);
        edDealerID.setAdapter(dealerAdapter);

        productAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, productsName);

        String[] unitItems = new String[]{"Packets", "Box"};
        unitAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, unitItems);

        String[] returnReasons = new String[]{"Expiry", "Damaged", "Breakage"};
        returnAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, returnReasons);

        for(int i=0; i<batchProductIds.size(); i++)
        {
            batchAdapter[i] = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, batchwiseStock.get(i));
        }
        btnSubmitOrder = rootView.findViewById(R.id.btn_send);
        btnSaveOrder = rootView.findViewById(R.id.btn_save);

        for(int i=0; i<4; i++)
        {
            extraCount++;
            lv.addView(createLinearLayout());
            addListenerToButtons();
        }
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                extraCount++;
//                lv.addView(createLinearLayout());
//                addListenerToButtons();
                edDealerID.setSelection(1);
            }
        });

        btnSaveOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(compileOrder())
                {
                    objSendData.saveReturn("0", send_dealerId, send_productIds, send_quantities, send_unit, send_batchno, send_return_price, String.valueOf(returnTotalPrice), send_return_reason, send_cash_return, GlobalVariables.getLatitude(), GlobalVariables.getLongitude(), GlobalVariables.getLocationNameHalf(), GlobalVariables.getStDate(), GlobalVariables.getStTime(), GlobalVariables.getUserId());
                }
            }
        });


        edProgress = rootView.findViewById(R.id.ed_progress);
        btnSubmitOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(compileOrder())
                {
                    objSendData.sendReturn("0", send_dealerId, send_productIds, send_quantities, send_unit, send_batchno, send_return_price, String.valueOf(returnTotalPrice), send_return_reason, send_cash_return, GlobalVariables.getLatitude(), GlobalVariables.getLongitude(), GlobalVariables.getLocationNameHalf(), GlobalVariables.getStDate(), GlobalVariables.getStTime(), GlobalVariables.getUserId());
                }
            }
        });
        return rootView;
    }

    public boolean compileOrder()
    {
        boolean check = false;
        if(edDealerID.getSelectedItemPosition() > 0)
        {
            send_dealerId = dealersId[edDealerID.getSelectedItemPosition()];
        }
        else
        {
            Toast.makeText(getActivity(), "Please Select Dealer", Toast.LENGTH_LONG).show();
            return false;
        }
        edProgress.setVisibility(View.VISIBLE);
        for(int j=0; j<extraCount; j++)
        {
            if(!(subLayout[j].getVisibility() == View.GONE) && extraProducts[j].getSelectedItemPosition() > 0)
            {
                if(check)
                {
                    send_productIds = send_productIds+"_-_"+productsIds[extraProducts[j].getSelectedItemPosition()];
                    send_quantities = send_quantities+"_-_"+extraQuantity[j].getText().toString();
                    send_return_price = send_return_price+"_-_"+(productsPrice[extraProducts[j].getSelectedItemPosition()] * Integer.parseInt(extraQuantity[j].getText().toString()));
                    send_batchno = send_batchno+"_-_"+extraBatch[j].getSelectedItem().toString();
                    returnTotalPrice = returnTotalPrice + (productsPrice[extraProducts[j].getSelectedItemPosition()] * Integer.parseInt(extraQuantity[j].getText().toString()));
                    send_unit = send_unit+"_-_"+extraUnits[j].getSelectedItem().toString();
                    send_return_reason = send_return_reason+"_-_"+returnReason[j].getSelectedItem().toString();
                }
                else
                {
                    send_productIds = productsIds[extraProducts[j].getSelectedItemPosition()];
                    send_quantities = extraQuantity[j].getText().toString();
                    send_return_price = String.valueOf(productsPrice[extraProducts[j].getSelectedItemPosition()] * Integer.parseInt(extraQuantity[j].getText().toString()));
                    send_batchno = extraBatch[j].getSelectedItem().toString();
                    send_unit = extraUnits[j].getSelectedItem().toString();
                    send_return_reason = returnReason[j].getSelectedItem().toString();
                    returnTotalPrice = returnTotalPrice + (Float.parseFloat(send_return_price));
                    check = true;
                }

            }
        }
        send_cash_return = edCashReturn.getText().toString();
        if(send_cash_return.equals(""))
        {
            send_cash_return = "0";
        }
        return true;
    }

    public SearchableSpinner createProductSpinner() {
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(Math.round(getResources().getDimension(R.dimen.return_product)), Math.round(getResources().getDimension(R.dimen.control_height)));
        extraProducts[extraCount-1] = new SearchableSpinner(getActivity());
        extraProducts[extraCount-1].setLayoutParams(lparams);
        extraProducts[extraCount-1].setAdapter(productAdapter);
        return extraProducts[extraCount-1];
    }

    public EditText createQuantityEditText() {
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(Math.round(getResources().getDimension(R.dimen.return_quantity)), Math.round(getResources().getDimension(R.dimen.control_height)));
        extraQuantity[extraCount-1] = new EditText(getActivity());
        extraQuantity[extraCount-1].setLayoutParams(lparams);
        extraQuantity[extraCount-1].setMovementMethod(new ScrollingMovementMethod());
        extraQuantity[extraCount-1].setText("1");
        extraQuantity[extraCount-1].setInputType(InputType.TYPE_CLASS_NUMBER);
        extraQuantity[extraCount-1].setFilters(new InputFilter[]{ new InputFilterMinMax("1", "100")});
        extraQuantity[extraCount-1].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
        return extraQuantity[extraCount-1];
    }


    public Spinner createUnitSpinner() {
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(Math.round(getResources().getDimension(R.dimen.return_unit)), Math.round(getResources().getDimension(R.dimen.control_height)));
        extraUnits[extraCount-1] = new Spinner(getActivity());
        extraUnits[extraCount-1].setLayoutParams(lparams);
        extraUnits[extraCount-1].setAdapter(unitAdapter);
        return extraUnits[extraCount-1];
    }

    public SearchableSpinner createBatchSpinner() {
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, Math.round(getResources().getDimension(R.dimen.control_height)));
        extraBatch[extraCount-1] = new SearchableSpinner(getActivity());
        extraBatch[extraCount-1].setLayoutParams(lparams);
//        extraBatch[extraCount-1].setAdapter(batchAdapter[1]);
        return extraBatch[extraCount-1];
    }

    public SearchableSpinner createReturnReasonSpinner() {
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(Math.round(getResources().getDimension(R.dimen.return_reason)), Math.round(getResources().getDimension(R.dimen.control_height)));
        returnReason[extraCount-1] = new SearchableSpinner(getActivity());
        returnReason[extraCount-1].setLayoutParams(lparams);
        returnReason[extraCount-1].setAdapter(returnAdapter);
        return returnReason[extraCount-1];
    }

    public Button createOpButton() {
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        extraOpBtn[extraCount-1] = new Button(getActivity());
        extraOpBtn[extraCount-1].setLayoutParams(lparams);
        extraOpBtn[extraCount-1].setText("X");
        extraOpBtn[extraCount-1].setTextColor(Color.RED);
        extraOpBtn[extraCount-1].setBackgroundColor(Color.TRANSPARENT);
        return extraOpBtn[extraCount-1];
    }

    public LinearLayout createDetailLinearLayout1() {
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        subLayoutDetail1[extraCount-1] = new LinearLayout(getActivity());
        subLayoutDetail1[extraCount-1].setOrientation(LinearLayout.HORIZONTAL);
        subLayoutDetail1[extraCount-1].setLayoutParams(lparams);
        subLayoutDetail1[extraCount-1].addView(createProductSpinner());
        subLayoutDetail1[extraCount-1].addView(createBatchSpinner());
        return subLayoutDetail1[extraCount-1];
    }

    public LinearLayout createDetailLinearLayout2() {
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        subLayoutDetail2[extraCount-1] = new LinearLayout(getActivity());
        subLayoutDetail2[extraCount-1].setOrientation(LinearLayout.HORIZONTAL);
        subLayoutDetail2[extraCount-1].setLayoutParams(lparams);
        subLayoutDetail2[extraCount-1].addView(createQuantityEditText());
        subLayoutDetail2[extraCount-1].addView(createUnitSpinner());
        subLayoutDetail2[extraCount-1].addView(createReturnReasonSpinner());
        subLayoutDetail2[extraCount-1].addView(createOpButton());
        return subLayoutDetail2[extraCount-1];
    }

    public LinearLayout createLinearLayout() {
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        subLayout[extraCount-1] = new LinearLayout(getActivity());
        subLayout[extraCount-1].setOrientation(LinearLayout.VERTICAL);
        subLayout[extraCount-1].setLayoutParams(lparams);
        subLayout[extraCount-1].addView(createDetailLinearLayout1());
        subLayout[extraCount-1].addView(createDetailLinearLayout2());
        return subLayout[extraCount-1];
    }

    public void addListenerToButtons()
    {
        for(int i=0; i<extraCount; i++)
        {
            final int finalI = i;
            extraOpBtn[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    subLayout[finalI].setVisibility(View.GONE);
                    calculatePrice();
                }
            });

            extraProducts[i].setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    int pos = extraProducts[finalI].getSelectedItemPosition();
                    String selectedId = productsIds[pos];
                    int index = findIndexInArray(selectedId, batchIds);
                    if(index >= 0)
                    {
                        extraBatch[finalI].setAdapter(batchAdapter[index]);
                        calculatePrice();
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            extraQuantity[i].setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean hasFocus) {
                    if (!hasFocus) {
                        if(extraQuantity[finalI].getText().toString().equals(""))
                        {
                            extraQuantity[finalI].setText("1");
                        }
                        calculatePrice();
                    }
                }
            });

            extraQuantity[i].addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    calculatePrice();
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    calculatePrice();
                }

                @Override
                public void afterTextChanged(Editable s) {
                    calculatePrice();
                }
            });
        }
        calculatePrice();
    }

    public void calculatePrice()
    {
        orderPrice = 0f;
        finalPrice = 0f;
        for(int j=0; j<extraCount; j++)
        {
            if(!(subLayout[j].getVisibility() == View.GONE))
            {
                String stQan = extraQuantity[j].getText().toString();
                if(stQan.equals(""))
                {
                    stQan = "0";
                }
                orderPrice = orderPrice + (productsPrice[extraProducts[j].getSelectedItemPosition()] * Integer.parseInt(stQan));
            }
        }
        finalPrice = orderPrice - ((orderPrice/100)*discount);
        edOrderPrice.setText(String.valueOf(orderPrice));

    }

    protected void displayReceivedData(String message)
    {
        Toast.makeText(getActivity(), "Return Message: "+message, Toast.LENGTH_LONG).show();
        editPrevious = true;
        editReturnId = message;
        GetData objGetData = new GetData(getActivity());
        Cursor res = objGetData.getPendingReturnDetail(editReturnId);
        res.moveToNext();
        editDealerId = res.getString(2);
        editProductId = res.getString(3);
        String[] editProductIdArr = editProductId.split("_-_");
        editBatch = res.getString(6);
        String[] editBatchArr = editBatch.split("_-_");
        editQuantity = res.getString(4);
        String[] editQuantityArr = editQuantity.split("_-_");
        editUnit = res.getString(5);
        String[] editUnitArr = editUnit.split("_-_");
        editReason = res.getString(9);
        String[] editReasonArr = editReason.split("_-_");
        editReturnPrice = res.getString(8);
        editCashReturn = res.getString(10);

        int dealerIndex = findIndexInArray(editDealerId, dealersId);
        edDealerID.setSelection(dealerIndex);
        edOrderPrice.setText(editReturnPrice);
        edCashReturn.setText(editCashReturn);
    }
}

0 个答案:

没有答案