Изменение Time Picker приводит к сбою приложения - PullRequest
0 голосов
/ 28 августа 2018

Минутный диапазон на сборщике времени, чтобы использовать приведенный ниже код Java, все работает правильно, сборщик времени устанавливает диапазон на 0 и 30 минут, но когда я делаю слайд на сборщике времени, чтобы изменить минуты, приложение останавливается и показать это сообщение: GC_FOR_ALLOC освобожден 1582K, 50% свободен 8434K / , сообщение очевидно из-за сборщика мусора и появляется несколько раз, как приложение может блокировать само? Как я могу решить это? (Я утверждаю, что один и тот же код я использую уже в разных точках своего приложения, и у меня никогда не было проблем)

Java-код:

public class GestioneRisorseUmaneActivity extends AppCompatActivity {

private Spinner spinnerRisorseUmane;
private TextView mDisplayDate;
private EditText txtNote;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private TimePicker OrePickerInzio, OrePickerFine, OrePickerPausa;
private ArrayList RisorseCantiere = new ArrayList();
private RisorsaUmana risorseumanaCantiere;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gestione_risorse_umane);
    try {
        //Recupero L'intent Cotenente le informazioni dell'utente
        Intent i = this.getIntent();
        final User u = (User) i.getSerializableExtra("User");
        final Cantiere cl = (Cantiere) i.getSerializableExtra("Cantiere");
        //Inzializzo lo Spinner
        spinnerRisorseUmane = findViewById(R.id.spinnerRisorseUmane);
        //Inizio Configurazione Spinner
        ArrayList arraySpinner = RisorsaUmana.CaricaRisorseUmane();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, arraySpinner);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerRisorseUmane.setAdapter(adapter);

        //Inizalizzione TextView Data e EditText Note e switch Rapportino
        mDisplayDate = findViewById(R.id.textViewData);
        txtNote = findViewById(R.id.EditTextNote);
        final Switch switchRapportino = findViewById(R.id.switchRapportino);

        mDisplayDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                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 dialog = new DatePickerDialog(
                        GestioneRisorseUmaneActivity.this,
                        android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                        mDateSetListener,
                        year, month, day);
                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog.show();
            }
        });

        mDateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                month = month + 1;
                String date = day + "/" + month + "/" + year;
                mDisplayDate.setText(date);
            }
        };

        //Configuro la TextView della data sul giorno corrente
        mDisplayDate.setText(Support.GetCurrentDay());
        //Configurazione TimePicker Ore Inzio
        OrePickerInzio = findViewById(R.id.TimePickerOreInizio);
        OrePickerInzio.setIs24HourView(true);
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
        Date dateDefault = null;
        try {
            dateDefault = sdf.parse("08:00");
        } catch (ParseException e) {
        }
        Calendar c = Calendar.getInstance();
        c.setTime(dateDefault);
        //TimePicker picker = new TimePicker(getApplicationContext());
        OrePickerInzio.setCurrentHour(c.get(Calendar.HOUR_OF_DAY));
        OrePickerInzio.setCurrentMinute(c.get(Calendar.MINUTE));
        //Configurazione TimePicker Ore Fine
        OrePickerFine = findViewById(R.id.TimePickerOreFine);
        OrePickerFine.setIs24HourView(true);
        sdf = new SimpleDateFormat("hh:mm");
        dateDefault = null;
        try {
            dateDefault = sdf.parse("17:30");
        } catch (ParseException e) {
        }
        OrePickerFine.setCurrentHour(c.get(Calendar.HOUR_OF_DAY));
        OrePickerFine.setCurrentMinute(c.get(Calendar.MINUTE));
        //Configurazione TimePicker Ore Pausa
        OrePickerPausa = (TimePicker)findViewById(R.id.timepickerorepausa);
        OrePickerPausa.setIs24HourView(true);
        sdf = new SimpleDateFormat("hh:mm");
        dateDefault = null;
        try {
            dateDefault = sdf.parse("01:30");
        } catch (ParseException e) {
        }
        //Imposto il range di minuti personalizzati sul timepicker e disabilito l'inserimento testuale sui timepicker
        Support.setTimePickerInterval(OrePickerInzio);
        Support.setTimePickerInterval(OrePickerFine);

        //Call of function set timepicker 
        Support.setTimePickerInterval(OrePickerPausa);
        OrePickerInzio.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
        OrePickerFine.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
        OrePickerPausa.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);

        //Configurazione Bottone inserimento Risorse Umane
        final Button buttonInserimentoRisorsa = findViewById(R.id.buttonInserimentoRisorsaUmana);
        buttonInserimentoRisorsa.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                int OreInzio, OreFine;

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    OreInzio = OrePickerInzio.getHour();
                    OreFine = OrePickerFine.getMinute();
                } else {
                    OreInzio = Integer.parseInt(OrePickerInzio.getCurrentHour().toString());
                    OreFine = Integer.parseInt(OrePickerFine.getCurrentHour().toString());
                }

                //Verifico che OreFine sia maggiore di OreInizio
                if (OreFine > OreInzio) {

                    //Verifico che le Note siano inserite
                    if (txtNote.getText().length() > 0) {

                        //Verifico che la Data sia inserita
                        if (mDisplayDate.getText() != "") {
                            //Creo l'oggetto utemp che rappresenta l'utente che verrà inserinto nel cantiere
                            User utemp = new User(spinnerRisorseUmane.getSelectedItem().toString());
                            String oreStart = null, oreEnd = null, orePausa = null;

                            /*
                               Carico dentro le stringhe oreStart e oreEnd le ore inizio e ore fine selezionate
                               dall'utente selezionate in base alla versione di Android che l'utente sta utilizzando

                             */
                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                                oreStart = "" + OrePickerInzio.getHour() + ":" + OrePickerInzio.getMinute();
                                oreEnd = "" + OrePickerFine.getHour() + ":" + OrePickerFine.getMinute();
                                orePausa = "" + OrePickerPausa.getHour() + ":" + OrePickerPausa.getMinute();


                            } else {
                                oreStart = "" + OrePickerInzio.getCurrentHour() + ":" + OrePickerInzio.getCurrentMinute();
                                oreEnd = "" + OrePickerFine.getCurrentHour() + ":" + OrePickerFine.getCurrentMinute();
                                orePausa = "" + OrePickerPausa.getCurrentHour() + "." + OrePickerPausa.getCurrentMinute();
                            }
                            oreStart = Support.ConvertStringToDate(oreStart, true);
                            oreEnd = Support.ConvertStringToDate(oreEnd, true);


                            String Date = Support.ConvertStringToDate(mDisplayDate.getText().toString(), false);

                            RisorsaUmana r = new RisorsaUmana(cl);
                            Boolean IsRapportino = switchRapportino.isChecked();
                            if (r.InseritaCantiere(utemp, u, IsRapportino, oreStart, oreEnd, orePausa, Date, txtNote.getText().toString()) == true) {

                                AggionaListiViewRisorse();
                            } else {
                                Support.Notification(GestioneRisorseUmaneActivity.this, "Errore", "Risorsa non inserita");
                            }
                        } else {
                            Support.Notification(GestioneRisorseUmaneActivity.this, "Errore", "Data non corretta");
                        }

                    } else {
                        Support.Notification(GestioneRisorseUmaneActivity.this, "Errore", "Note non inserite");
                    }

                } else {
                    Support.Notification(GestioneRisorseUmaneActivity.this, "Errore", "Ore non corrette");
                }
            }
        });

        //Inizalizzazione RisorseUmana
        risorseumanaCantiere = new RisorsaUmana(cl);
    } catch (Exception ex) {
        ErrorManagement.SendError("Errore caricamento finestra risorse Umane");
    }
    //Aggiorno lista risorse umane
    AggionaListiViewRisorse();
}

//Questa funzione si occupa di aggiornare gli articoli presenti nella ListView
private void AggionaListiViewRisorse() {

    //Listview che visulizza gli Articoli con il CustomAdapter
    ListView risorseListView = findViewById(R.id.ListViewRisorseUmane);
    GestioneRisorseUmaneActivity.CustomAdapterRisorse cm = new GestioneRisorseUmaneActivity.CustomAdapterRisorse();
    risorseListView.setAdapter(cm);
    RisorseCantiere = risorseumanaCantiere.CaricaRisorseUmaneCantiere();
}

class CustomAdapterRisorse extends BaseAdapter {

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

    @Override
    public Object getItem(int position) {

        return null;
    }


    @Override
    public long getItemId(int position) {

        return 0;
    }


    protected void onPostExecute(int position) {


    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        convertView = getLayoutInflater().inflate(R.layout.row_articoli, null);
        TextView txtCodiceArticolo = convertView.findViewById(R.id.textView_CodiceArticolo);
        TextView txtDescrizione = convertView.findViewById(R.id.textView_Descrizione);
        TextView txtPrezzo = convertView.findViewById(R.id.textView_Prezzo);
        TextView txtQuantita = convertView.findViewById(R.id.textView_Quantita);

        RisorsaUmana r = (RisorsaUmana) RisorseCantiere.get(position);

        txtCodiceArticolo.setText("" + r.GetNome() + " " + r.GetCognome());
        txtDescrizione.setText(r.getDescrizione());
        txtPrezzo.setText(r.getData());
        txtQuantita.setText("Ore: " + r.getTotaleOre());
        return convertView;
    }


}

}

// Эта функция устанавливает время выбора минут на интервал 30 минут

 public static synchronized void setTimePickerInterval(TimePicker timePicker) {
        try {
            int TIME_PICKER_INTERVAL = 30;
            NumberPicker minutePicker = (NumberPicker) timePicker.findViewById(Resources.getSystem().getIdentifier(
                    "minute", "id", "android"));
            minutePicker.setMinValue(0);
            minutePicker.setMaxValue((60 / TIME_PICKER_INTERVAL) - 1);
            List<String> displayedValues = new ArrayList<String>();
            for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
                displayedValues.add(String.format("%02d", i));
            }
            minutePicker.setDisplayedValues(displayedValues.toArray(new String[0]));
        } catch (Exception ex) {
            ErrorManagement.SendError("error " + timePicker.toString() + "\n errore:" + ex);
        }
    }

XML-код:

<TimePicker
        android:id="@+id/timepickerorepausa"
        android:layout_width="231dp"
        android:layout_height="81dp"
        android:layout_marginLeft="90dp"
        android:layout_marginTop="280dp"
        android:timePickerMode="spinner">

LogCat:

Ошибка:

E / dalvikvm: Не удалось найти класс 'android.widget.ThemedSpinnerAdapter', на который ссылается метод android.support.v7.widget.AppCompatSpinner $ DropDownAdapter.

Debug

    08-28 12:36:16.386 10747-10747/mycompany.myapp I/Choreographer: Skipped 37 frames!  The application may be doing too much work on its main thread.
    08-28 12:36:21.912 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 6507K, 49% free 8534K/16700K, paused 35ms, total 36ms
    08-28 12:36:22.343 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1106K, 50% free 8452K/16700K, paused 19ms, total 19ms
    08-28 12:36:22.693 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1024K, 50% free 8451K/16700K, paused 20ms, total 20ms
    08-28 12:36:23.224 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1600K, 50% free 8451K/16700K, paused 21ms, total 21ms
    08-28 12:36:23.604 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1023K, 50% free 8451K/16700K, paused 19ms, total 19ms
    08-28 12:36:23.984 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1024K, 50% free 8451K/16700K, paused 19ms, total 19ms
    08-28 12:36:24.525 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1600K, 50% free 8451K/16700K, paused 27ms, total 27ms
    08-28 12:36:24.945 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1024K, 50% free 8451K/16700K, paused 20ms, total 20ms
    08-28 12:36:25.346 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1023K, 50% free 8451K/16700K, paused 19ms, total 19ms
    08-28 12:36:25.906 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1600K, 50% free 8451K/16700K, paused 20ms, total 20ms
    08-28 12:36:26.297 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1024K, 50% free 8451K/16700K, paused 19ms, total 19ms
    08-28 12:36:26.707 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1023K, 50% free 8451K/16700K, paused 19ms, total 19ms
    08-28 12:36:27.268 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1600K, 50% free 8451K/16700K, paused 21ms, total 21ms
    08-28 12:36:27.678 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1024K, 50% free 8451K/16700K, paused 19ms, total 19ms
    08-28 12:36:28.059 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1024K, 50% free 8451K/16700K, paused 18ms, total 19ms
    08-28 12:36:28.579 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1599K, 50% free 8451K/16700K, paused 21ms, total 21ms
    08-28 12:36:28.950 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1023K, 50% free 8451K/16700K, paused 19ms, total 19ms
    08-28 12:36:29.330 10747-10747/mycompany.myapp D/dalvikvm: GC_FOR_ALLOC freed 1023K, 50% free 8451K/16700K, paused 18ms, total 18ms
    08-28 12:36:29.861 10747-10747/mycompany.myapp D/dalvikvm: 
....
...