cl.smartcities.isci.transportinspector.dialogs.BusSelectionDialog.java Source code

Java tutorial

Introduction

Here is the source code for cl.smartcities.isci.transportinspector.dialogs.BusSelectionDialog.java

Source

package cl.smartcities.isci.transportinspector.dialogs;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import cl.smartcities.isci.transportinspector.R;
import cl.smartcities.isci.transportinspector.adapters.dialogAdapters.BusSelectionAdapter;
import cl.smartcities.isci.transportinspector.backend.Bus;
import cl.smartcities.isci.transportinspector.database.ServiceHelper;
import cl.smartcities.isci.transportinspector.detectionService.states.NotificationState;
import cl.smartcities.isci.transportinspector.utils.Constants;
import cl.smartcities.isci.transportinspector.utils.LicensePlateValidator;
import cl.smartcities.isci.transportinspector.utils.ServiceValidator;
import cl.smartcities.isci.transportinspector.utils.Util;

/**
 * Created by Felipe onStopListener 24-09-2015.
 * <p/>
 * DialogFragment that shows a list of buses that the user might have taken.
 */
public class BusSelectionDialog extends DialogFragment {
    private HashMap<String, ArrayList<Bus>> busMap;
    private BusSelectionAdapter.ListViewAdapterListener listener;
    private static final int VISIBLE_BUSES = 4;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            listener = (BusSelectionAdapter.ListViewAdapterListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString() + " must implement NoticeDialogListener");
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

        LayoutInflater inflater = this.getActivity().getLayoutInflater();
        final View dialog_view = inflater.inflate(R.layout.bus_selection_dialog, null);
        final Typeface iconTypeface = Typeface.createFromAsset(this.getContext().getAssets(),
                getActivity().getString(R.string.icon_font));
        ((TextView) dialog_view.findViewById(R.id.suggestion_icon)).setTypeface(iconTypeface);

        builder.setView(dialog_view);
        builder.setCancelable(false);
        dialog = builder.create();

        final Bundle bundle = getArguments();
        ArrayList<Bus> buses = null;

        if (bundle != null) {
            buses = bundle.getParcelableArrayList(NotificationState.BUSES);
        }

        if (buses != null && !buses.isEmpty()) {
            dialog_view.findViewById(R.id.list_view).setVisibility(View.VISIBLE);
            setBusMap(buses);
            ArrayList<String> serviceList = new ArrayList<>();
            serviceList.addAll(this.busMap.keySet());
            BusSelectionAdapter adapter = new BusSelectionAdapter(this.getContext(), serviceList, busMap,
                    new BusSelectionAdapter.ListViewAdapterListener() {
                        @Override
                        public void onPositiveClick(Bus bus) {
                            dialog.cancel();
                            listener.onPositiveClick(bus);
                        }

                        @Override
                        public void onNegativeClick() {
                            dialog.cancel();
                            listener.onNegativeClick();
                        }
                    });
            ListView listView = (ListView) dialog_view.findViewById(R.id.list_view);

            listView.setAdapter(adapter);

            if (adapter.getCount() > VISIBLE_BUSES) {
                View item = adapter.getView(0, null, listView);
                item.measure(0, 0);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        (int) ((VISIBLE_BUSES + 0.5) * item.getMeasuredHeight()));
                listView.setLayoutParams(params);
            }

        }

        Button otherAcceptButton = (Button) dialog_view.findViewById(R.id.accept);
        otherAcceptButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText serviceEditText = (EditText) dialog_view.findViewById(R.id.service_edit_text);
                EditText licensePlateEditText = (EditText) dialog_view.findViewById(R.id.license_plate_edit_text);
                String service = serviceEditText.getText().toString();
                String licensePlate = licensePlateEditText.getText().toString();
                ServiceHelper helper = new ServiceHelper(getContext());

                if (ServiceValidator.validate(service) && helper.getColorId(Util.formatServiceName(service)) != 0) {
                    service = Util.formatServiceName(service);
                    if (licensePlate.equals("")) {
                        licensePlate = Constants.DUMMY_LICENSE_PLATE;
                    } else if (!LicensePlateValidator.validate(licensePlate)) {
                        Toast.makeText(getContext(), R.string.bus_selection_warning_plate, Toast.LENGTH_SHORT)
                                .show();
                        return;
                    }
                } else {
                    Toast.makeText(getContext(), R.string.bus_selection_warning_service, Toast.LENGTH_SHORT).show();
                    return;
                }

                final Bus bus = new Bus(Util.formatServiceName(service), licensePlate);
                InputMethodManager imm = (InputMethodManager) getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

                Log.d("BusSelectionDialog", "hiding soft input");

                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        BusSelectionDialog.this.getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dialog.cancel();
                                listener.onPositiveClick(bus);
                            }
                        });
                    }
                }, 500);
                //dialog.cancel();
                // TODO(aantoine): This call is to quick, some times the keyboard is not
                // out of the window when de sliding panel shows up.
                //listener.onPositiveClick(bus);
            }
        });

        /* set cancel button to close dialog */
        dialog_view.findViewById(R.id.close_dialog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
                listener.onNegativeClick();
            }
        });
        ((Button) dialog_view.findViewById(R.id.close_dialog)).setTypeface(iconTypeface);
        dialog.setCanceledOnTouchOutside(false);

        return dialog;
    }

    /**
     * Creates a hashMap using a list of buses. This hashMap needed for the adapter.
     *
     */
    private void setBusMap(ArrayList<Bus> busList) {
        this.busMap = new HashMap<>();
        for (Bus bus : busList) {
            String service = bus.getService();
            //If the map does not contain the service
            if (!this.busMap.containsKey(service)) {
                ArrayList<Bus> sameServiceBusList = new ArrayList<>();
                sameServiceBusList.add(bus);
                this.busMap.put(service, sameServiceBusList);
            } else {
                ArrayList<Bus> sameServiceBusList = this.busMap.get(service);
                sameServiceBusList.add(bus);
            }
        }
    }
}