一个活动中的多个Spinner与phpmyadmin中的不同表

时间:2019-05-16 06:57:24

标签: android android-spinner

我正在创建一个需要多个微调器的应用程序。微调器上的数据将来自phpmyadmin,但位于不同的表中。例如,用于商店代码的微调器和用于银行的微调器,就像在我的应用程序中一样。现在让我们说商店代码表有15个项目,银行表只有10个项目,它们解析就很好了。但是问题是,如果我单击商店代码微调器中的11-15个项目之一,则会崩溃。如果表具有相同数量的项目,它们可以正常工作,但是如果一个表具有多个项目,则崩溃。我该如何处理我的代码?

Java文件的代码

public class DailySales extends AppCompatActivity implements AdapterView.OnItemSelectedListener{

    ArrayList<String> banknames=new ArrayList<>();
    ArrayList<String> storecodes=new ArrayList<>();
    ArrayAdapter<String> adapter1, adapter2, adapter3, adapter4, adapter5;
    String storecode, spinner2, spinner3, spinner4, spinner5;
    TextView TVCash, TVCredita, TVCreditb, TVDebita, TVDebitb, TVEcpv, TVGc, TVSd, Salesdate;
    EditText Cash, CreditA, CreditB, DebitA, DebitB, Ecpv, Gc, Sd;
    Spinner Storecode, Spinner2, Spinner3, Spinner4, Spinner5;
    Button submit;
    DatePickerDialog datePickerDialog;

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

        drawerLayout = (DrawerLayout) findViewById(drawer);
        toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
        drawerLayout.addDrawerListener(toggle);
        toggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        NavigationView navigationView=(NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        Cash = (EditText) findViewById(R.id.cash);
        CreditA = (EditText) findViewById(R.id.credita);
        CreditB = (EditText) findViewById(R.id.creditb);
        DebitA = (EditText) findViewById(R.id.debita);
        DebitB = (EditText) findViewById(R.id.debitb);
        Ecpv = (EditText) findViewById(R.id.ecpv);
        Gc = (EditText) findViewById(R.id.gc);
        Sd = (EditText) findViewById(R.id.sd);

        Salesdate = (TextView) findViewById(R.id.salesdate);

        TVCash = (TextView) findViewById(R.id.textviewcash);
        TVCredita = (TextView) findViewById(R.id.textviewcredita);
        TVCreditb = (TextView) findViewById(R.id.textviewcreditb);
        TVDebita = (TextView) findViewById(R.id.textviewdebita);
        TVDebitb = (TextView) findViewById(R.id.textviewdebitb);
        TVEcpv = (TextView) findViewById(R.id.textviewecpv);
        TVGc = (TextView) findViewById(R.id.textviewgc);
        TVSd = (TextView) findViewById(R.id.textviewsd);

        Storecode = (Spinner) findViewById(R.id.storecode);
        adapter1 = new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,storecodes);
        Storecode.setAdapter(adapter1);
        Storecode.setOnItemSelectedListener(this);

        Spinner2 = (Spinner) findViewById(R.id.spinner2);
        adapter2 = new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,banknames);
        Spinner2.setAdapter(adapter2);
        Spinner2.setOnItemSelectedListener(this);

        Spinner3 = (Spinner) findViewById(R.id.spinner3);
        adapter3 = new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,banknames);
        Spinner3.setAdapter(adapter3);
        Spinner3.setOnItemSelectedListener(this);

        Spinner4 = (Spinner) findViewById(R.id.spinner4);
        adapter4 = new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,banknames);
        Spinner4.setAdapter(adapter4);
        Spinner4.setOnItemSelectedListener(this);

        Spinner5 = (Spinner) findViewById(R.id.spinner5);
        adapter5 = new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,banknames);
        Spinner5.setAdapter(adapter5);
        Spinner5.setOnItemSelectedListener(this);

        Salesdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH);
                int day = cal.get(Calendar.DAY_OF_MONTH);

                datePickerDialog = new DatePickerDialog(DailySales.this, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        Salesdate.setText(year+"-"+(month+1)+"-"+dayOfMonth);
                    }
                }, year,month,day);
                datePickerDialog.show();
            }
        });

        submit = (Button)findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(DailySales.this);
                builder.setMessage("Are you sure about the informations?")
                        .setCancelable(false)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (Salesdate.getText().toString().isEmpty()) {
                                    Salesdate.setError("Pick a date");
                                } else if (Cash.length() == 0 && CreditA.length() == 0 && CreditB.length() == 0
                                        && DebitA.length() == 0 && DebitB.length() == 0 && Ecpv.length() == 0 &&
                                        Gc.length() == 0 && Sd.length() == 0){
                                    opendialog();
                                } else {
                                    dailysales();
                                }
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                AlertDialog alertDialog=builder.create();
                alertDialog.show();
            }
        });
    }

    public void opendialog(){
        ExampleDialog exampleDialog = new ExampleDialog();
        exampleDialog.show(getSupportFragmentManager(), "example dialog");
    }

    public void dailysales(){
        StringRequest request = new StringRequest(Request.Method.POST, "(I will not show the url)", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.contains("1")) {
                    startActivity(new Intent(getApplicationContext(), DailySales.class));
                    Toast.makeText(getApplicationContext(), "Data Added Successfully!", Toast.LENGTH_LONG).show();
                } else if(response.contains("2")) {
                    Toast.makeText(getApplicationContext(), "Data does not added successfully!", Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                //DATE PICKER
                params.put("salesdate",Salesdate.getText().toString());
                //SPINNERS
                params.put("storecode",Storecode.getSelectedItem().toString());
                params.put("spinner2",Spinner2.getSelectedItem().toString());
                params.put("spinner3",Spinner3.getSelectedItem().toString());
                params.put("spinner4",Spinner4.getSelectedItem().toString());
                params.put("spinner5",Spinner5.getSelectedItem().toString());
                //TEXT VIEWS
                params.put("tvcash",TVCash.getText().toString());
                params.put("tvcredita",TVCredita.getText().toString());
                params.put("tvcreditb",TVCreditb.getText().toString());
                params.put("tvdebita",TVDebita.getText().toString());
                params.put("tvdebitb",TVDebitb.getText().toString());
                params.put("tvecpv",TVEcpv.getText().toString());
                params.put("tvgc",TVGc.getText().toString());
                params.put("tvsd",TVSd.getText().toString());
                //EDIT TEXTS
                params.put("cash",Cash.getText().toString());
                params.put("credita",CreditA.getText().toString());
                params.put("creditb",CreditB.getText().toString());
                params.put("debita",DebitA.getText().toString());
                params.put("debitb",DebitB.getText().toString());
                params.put("ecpv",Ecpv.getText().toString());
                params.put("gc",Gc.getText().toString());
                params.put("sd",Sd.getText().toString());
                return params;
            }
        };
        Volley.newRequestQueue(this).add(request);
    }

    public void onStart(){
        super.onStart();
        BackTask bt=new BackTask();
        bt.execute();
    }

    private class BackTask extends AsyncTask<Void, Void, Void> {
        ArrayList<String> list1;
        ArrayList<String> list2;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            list1 = new ArrayList<>();
            list2 = new ArrayList<>();
        }

        @Override
        protected Void doInBackground(Void... params) {
            InputStream is1 = null;
            InputStream is2 = null;
            String result1 = "";
            String result2 = "";
                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost("(I'm aware about the url)");
                    HttpResponse response = httpClient.execute(httpPost);
                    HttpEntity entity = response.getEntity();
                    is1 = entity.getContent();

                    HttpClient httpClient2 = new DefaultHttpClient();
                    HttpPost httpPost2 = new HttpPost("(I'm aware about the url)");
                    HttpResponse response2 = httpClient2.execute(httpPost2);
                    HttpEntity entity2 = response2.getEntity();
                    is2 = entity2.getContent();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(is1, "utf-8"));
                    String line1 = "";
                    while ((line1 = bufferedReader1.readLine()) != null) {
                        result1 = line1;
                    }
                    is1.close();

                    BufferedReader bufferedReader2 = new BufferedReader(new InputStreamReader(is2, "utf-8"));
                    String line2 = "";
                    while ((line2 = bufferedReader2.readLine()) != null) {
                        result2 = line2;
                    }
                    is2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    JSONArray jsonArray1 = new JSONArray(result1);
                    for (int i = 0; i < jsonArray1.length(); i++) {
                        JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
                        list1.add(jsonObject1.getString("storecode"));
                    }
                    JSONArray jsonArray2 = new JSONArray(result2);
                    for (int ii = 0; ii < jsonArray2.length(); ii++) {
                        JSONObject jsonObject2 = jsonArray2.getJSONObject(ii);
                        list2.add(jsonObject2.getString("bank_name"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            storecodes.addAll(list1);
            banknames.addAll(list2);
            adapter1.notifyDataSetChanged();
            adapter2.notifyDataSetChanged();
            adapter3.notifyDataSetChanged();
            adapter4.notifyDataSetChanged();
            adapter5.notifyDataSetChanged();

            List<String> Storecodes = new ArrayList<>(new LinkedHashSet<>(storecodes));
            Storecode.setAdapter(new ArrayAdapter<String>(DailySales.this,
                    android.R.layout.simple_spinner_dropdown_item, Storecodes));

            List<String> Banknames1 = new ArrayList<>(new LinkedHashSet<>(banknames));
            Spinner2.setAdapter(new ArrayAdapter<String>(DailySales.this,
                    android.R.layout.simple_spinner_dropdown_item, Banknames1));

            List<String> Banknames2 = new ArrayList<>(new LinkedHashSet<>(banknames));
            Spinner3.setAdapter(new ArrayAdapter<String>(DailySales.this,
                    android.R.layout.simple_spinner_dropdown_item, Banknames2));

            List<String> Banknames3 = new ArrayList<>(new LinkedHashSet<>(banknames));
            Spinner4.setAdapter(new ArrayAdapter<String>(DailySales.this,
                    android.R.layout.simple_spinner_dropdown_item, Banknames3));

            List<String> Banknames4 = new ArrayList<>(new LinkedHashSet<>(banknames));
            Spinner5.setAdapter(new ArrayAdapter<String>(DailySales.this,
                    android.R.layout.simple_spinner_dropdown_item, Banknames4));

            Collections.sort(storecodes);
            Collections.sort(banknames);
            Collections.sort(banknames);
            Collections.sort(banknames);
            Collections.sort(banknames);
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        storecode = Storecode.getItemAtPosition(position).toString();
        spinner2 = Spinner2.getItemAtPosition(position).toString();
        spinner3 = Spinner3.getItemAtPosition(position).toString();
        spinner4 = Spinner4.getItemAtPosition(position).toString();
        spinner5 = Spinner5.getItemAtPosition(position).toString();
    }

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

这是logcat中的错误

@Erythrozyt E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.(package name), PID: 29660
    java.lang.IndexOutOfBoundsException: Index: 10, Size: 10
        at java.util.ArrayList.get(ArrayList.java:437)
        at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:385)
        at android.widget.AdapterView.getItemAtPosition(AdapterView.java:798)
        at com.example.(package name).onItemSelected(DailySales.java:392)
        at android.widget.AdapterView.fireOnSelected(AdapterView.java:944)
        at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:933)
        at android.widget.AdapterView.-wrap1(Unknown Source:0)
        at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:898)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:187)
        at android.app.ActivityThread.main(ActivityThread.java:7025)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:514)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888

0 个答案:

没有答案