Example usage for android.widget LinearLayout removeAllViews

List of usage examples for android.widget LinearLayout removeAllViews

Introduction

In this page you can find the example usage for android.widget LinearLayout removeAllViews.

Prototype

public void removeAllViews() 

Source Link

Document

Call this method to remove all child views from the ViewGroup.

Usage

From source file:cm.aptoide.pt.MainActivity.java

private void loadRecommended() {

    if (Login.isLoggedIn(mContext)) {
        ((TextView) featuredView.findViewById(R.id.recommended_text)).setVisibility(View.GONE);
    } else {/*from  www. ja  v  a 2  s . co m*/
        ((TextView) featuredView.findViewById(R.id.recommended_text)).setVisibility(View.VISIBLE);
    }

    new Thread(new Runnable() {

        private ArrayList<HashMap<String, String>> valuesRecommended;

        public void run() {
            loadUIRecommendedApps();
            File f = null;
            try {
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                NetworkUtils utils = new NetworkUtils();
                BufferedInputStream bis = new BufferedInputStream(
                        utils.getInputStream("http://webservices.aptoide.com/webservices/listUserBasedApks/"
                                + Login.getToken(mContext) + "/10/xml", null, null, mContext),
                        8 * 1024);
                f = File.createTempFile("abc", "abc");
                OutputStream out = new FileOutputStream(f);
                byte buf[] = new byte[1024];
                int len;
                while ((len = bis.read(buf)) > 0)
                    out.write(buf, 0, len);
                out.close();
                bis.close();
                String hash = Md5Handler.md5Calc(f);
                ViewApk parent_apk = new ViewApk();
                parent_apk.setApkid("recommended");
                if (!hash.equals(db.getItemBasedApksHash(parent_apk.getApkid()))) {
                    // Database.database.beginTransaction();
                    db.deleteItemBasedApks(parent_apk);
                    sp.parse(f, new HandlerItemBased(parent_apk));
                    db.insertItemBasedApkHash(hash, parent_apk.getApkid());
                    // Database.database.setTransactionSuccessful();
                    // Database.database.endTransaction();
                    loadUIRecommendedApps();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            if (f != null)
                f.delete();

        }

        private void loadUIRecommendedApps() {

            valuesRecommended = db.getItemBasedApksRecommended("recommended");

            runOnUiThread(new Runnable() {

                public void run() {

                    LinearLayout ll = (LinearLayout) featuredView.findViewById(R.id.recommended_container);
                    ll.removeAllViews();
                    LinearLayout llAlso = new LinearLayout(MainActivity.this);
                    llAlso.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT));
                    llAlso.setOrientation(LinearLayout.HORIZONTAL);
                    if (valuesRecommended.isEmpty()) {
                        if (Login.isLoggedIn(mContext)) {
                            TextView tv = new TextView(mContext);
                            tv.setText(R.string.no_recommended_apps);
                            tv.setTextAppearance(mContext, android.R.attr.textAppearanceMedium);
                            tv.setPadding(10, 10, 10, 10);
                            ll.addView(tv);
                        }
                    } else {

                        for (int i = 0; i != valuesRecommended.size(); i++) {
                            LinearLayout txtSamItem = (LinearLayout) getLayoutInflater()
                                    .inflate(R.layout.row_grid_item, null);
                            ((TextView) txtSamItem.findViewById(R.id.name))
                                    .setText(valuesRecommended.get(i).get("name"));
                            ImageLoader.getInstance().displayImage(valuesRecommended.get(i).get("icon"),
                                    (ImageView) txtSamItem.findViewById(R.id.icon));
                            float stars = 0f;
                            try {
                                stars = Float.parseFloat(valuesRecommended.get(i).get("rating"));
                            } catch (Exception e) {
                                stars = 0f;
                            }
                            ((RatingBar) txtSamItem.findViewById(R.id.rating)).setIsIndicator(true);
                            ((RatingBar) txtSamItem.findViewById(R.id.rating)).setRating(stars);
                            txtSamItem.setPadding(10, 0, 0, 0);
                            // ((TextView)
                            // txtSamItem.findViewById(R.id.version))
                            // .setText(getString(R.string.version) +" "+
                            // valuesRecommended.get(i).get("vername"));
                            ((TextView) txtSamItem.findViewById(R.id.downloads))
                                    .setText("(" + valuesRecommended.get(i).get("downloads") + " "
                                            + getString(R.string.downloads) + ")");
                            txtSamItem.setTag(valuesRecommended.get(i).get("_id"));
                            txtSamItem.setLayoutParams(new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT, 100, 1));
                            // txtSamItem.setOnClickListener(featuredListener);
                            txtSamItem.setOnClickListener(new OnClickListener() {

                                @Override
                                public void onClick(View arg0) {
                                    Intent i = new Intent(MainActivity.this, ApkInfo.class);
                                    long id = Long.parseLong((String) arg0.getTag());
                                    i.putExtra("_id", id);
                                    i.putExtra("top", true);
                                    i.putExtra("category", Category.ITEMBASED.ordinal());
                                    startActivity(i);
                                }
                            });

                            txtSamItem.measure(0, 0);

                            if (i % 2 == 0) {
                                ll.addView(llAlso);

                                llAlso = new LinearLayout(MainActivity.this);
                                llAlso.setLayoutParams(new LinearLayout.LayoutParams(
                                        LinearLayout.LayoutParams.MATCH_PARENT, 100));
                                llAlso.setOrientation(LinearLayout.HORIZONTAL);
                                llAlso.addView(txtSamItem);
                            } else {
                                llAlso.addView(txtSamItem);
                            }
                        }

                        ll.addView(llAlso);
                    }
                }
            });
        }
    }).start();

}

From source file:com.mdlive.sav.MDLiveProviderDetails.java

/**
 *  Successful Response Handler for Load Provider Info.Here the Profile image of
 *  the Particular provider will be displayed.Along with that the Provider's
 *  speciality,about the Provider , license and the languages will also be
 *  displayed.Along with this Provider's affilitations will also be displayed
 *
 *//*from   www.ja va  2  s  . c  om*/
private void handleSuccessResponse(JSONObject response) {
    // DEBUGGING.  o.uwechue
    Log.d("MDLProviderDetails", "*********\nHTTP Response: " + response);
    try {
        //Fetch Data From the Services
        Log.d("Response details", "******************\n*******************\n" + response.toString());
        JsonParser parser = new JsonParser();
        JsonObject responObj = (JsonObject) parser.parse(response.toString());
        JsonObject profileobj = responObj.get("doctor_profile").getAsJsonObject();
        JsonObject providerdetObj = profileobj.get("provider_details").getAsJsonObject();

        JsonObject appointment_slot = profileobj.get("appointment_slot").getAsJsonObject();
        JsonArray available_hour = appointment_slot.get("available_hour").getAsJsonArray();

        boolean isDoctorWithPatient = false;
        LinearLayout layout = (LinearLayout) findViewById(R.id.panelMessageFiles);
        String str_timeslot = ""; /*str_phys_avail_id = "",*/
        SharedPreferences sharedpreferences = getSharedPreferences(PreferenceConstants.MDLIVE_USER_PREFERENCES,
                Context.MODE_PRIVATE);
        str_Availability_Type = sharedpreferences
                .getString(PreferenceConstants.PROVIDER_AVAILABILITY_TYPE_PREFERENCES, "");
        String str_avail_status = sharedpreferences
                .getString(PreferenceConstants.PROVIDER_AVAILABILITY_STATUS_PREFERENCES, "");
        if (str_avail_status.equalsIgnoreCase("true")) {
            if (str_Availability_Type.equalsIgnoreCase("video or phone")) {
                isDoctorAvailableNow = true;
            } else if (str_Availability_Type.equalsIgnoreCase("phone")) {
                isDoctorAvailableNow = true;
            } else if (str_Availability_Type.equalsIgnoreCase("video")) {
                isDoctorAvailableNow = true;
            }

            else if (str_Availability_Type.equalsIgnoreCase("With Patient")) {
                isDoctorAvailableNow = false;
            } else {
                isDoctorAvailableNow = false;
            }
        } else {
            isDoctorAvailableNow = false;
        }

        if (layout.getChildCount() > 0) {
            layout.removeAllViews();
        }
        videoList.clear();
        phoneList.clear();

        for (int i = 0; i < available_hour.size(); i++) {
            JsonObject availabilityStatus = available_hour.get(i).getAsJsonObject();
            String str_availabilityStatus = "";

            if (MdliveUtils.checkJSONResponseHasString(availabilityStatus, "status")) {
                str_availabilityStatus = availabilityStatus.get("status").getAsString();
                if (str_availabilityStatus.equals("Available")) {
                    JsonArray timeSlotArray = availabilityStatus.get("time_slot").getAsJsonArray();
                    for (int j = 0; j < timeSlotArray.size(); j++) {
                        JsonObject timeSlotObj = timeSlotArray.get(j).getAsJsonObject();

                        if (MdliveUtils.checkJSONResponseHasString(timeSlotObj, "appointment_type")
                                && MdliveUtils.checkJSONResponseHasString(timeSlotObj, "timeslot")) {
                            str_appointmenttype = timeSlotObj.get("appointment_type").getAsString();
                            str_timeslot = timeSlotObj.get("timeslot").getAsString();
                            selectedTimestamp = timeSlotObj.get("timeslot").getAsString();
                            Log.d("***TIMESLOT***", "****\n****\nTimeslot: [" + selectedTimestamp + "]");

                            if (MdliveUtils.checkJSONResponseHasString(timeSlotObj, "phys_availability_id")) {
                                str_phys_avail_id = timeSlotObj.get("phys_availability_id").getAsString();
                            } else {
                                str_phys_avail_id = null;
                            }

                            HashMap<String, String> map = new HashMap<String, String>();
                            map.put("timeslot", str_timeslot);
                            map.put("phys_id", (str_phys_avail_id == null) ? "" : str_phys_avail_id + "");
                            map.put("appointment_type", str_appointmenttype);

                            timeSlotListMap.add(map);
                            if (str_timeslot.equals("0")) {
                                if (!str_Availability_Type.equalsIgnoreCase("With Patient")) {
                                    final int density = (int) getBaseContext().getResources()
                                            .getDisplayMetrics().density;

                                    final Button myText = new Button(MDLiveProviderDetails.this);
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                        myText.setElevation(0f);
                                    }
                                    isDoctorAvailableNow = true;
                                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                                            LinearLayout.LayoutParams.WRAP_CONTENT,
                                            LinearLayout.LayoutParams.WRAP_CONTENT);
                                    params.setMargins(4 * density, 4 * density, 4 * density, 4 * density);
                                    myText.setLayoutParams(params);
                                    myText.setGravity(Gravity.CENTER);
                                    myText.setTextColor(Color.WHITE);
                                    myText.setTextSize(16);
                                    myText.setPadding(8 * density, 4 * density, 8 * density, 4 * density);
                                    myText.setBackgroundResource(R.drawable.timeslot_white_rounded_corner);
                                    myText.setText("Now");
                                    myText.setBackgroundResource(R.drawable.timeslot_blue_rounded_corner);
                                    myText.setClickable(true);
                                    previousSelectedTv = myText;
                                    if (str_appointmenttype.toLowerCase().contains("video")) {
                                        videoList.add(myText);
                                    }
                                    if (str_appointmenttype.toLowerCase().contains("phone")) {
                                        phoneList.add(myText);
                                    }
                                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                                            LinearLayout.LayoutParams.WRAP_CONTENT,
                                            LinearLayout.LayoutParams.WRAP_CONTENT);
                                    lp.setMargins(4 * density, 4 * density, 4 * density, 4 * density);
                                    myText.setLayoutParams(lp);
                                    myText.setTag("Now");
                                    defaultNowTextPreferences(myText, str_appointmenttype);
                                    selectedTimeslot = true;
                                    clickEventForHorizontalText(myText, str_timeslot, str_phys_avail_id);
                                    layout.addView(myText);
                                    //layout.addView(line, 1);
                                }
                            } else {
                                setHorizontalScrollviewTimeslots(layout, str_timeslot, j, str_phys_avail_id);
                            }
                        }
                    }
                } else if (str_availabilityStatus.equalsIgnoreCase("With patient")) {
                    isDoctorWithPatient = true;
                }
            }
        }

        //with patient
        if (isDoctorWithPatient) {
            if (layout.getChildCount() >= 1) {
                // Req Future Appmt

                enableOrdisableProviderDetails(str_Availability_Type);
            } else if (layout.getChildCount() < 1) {
                //Make future appointment
                onlyWithPatient();

            }
        }

        /*This is for Status is available and the timeslot is Zero..Remaining all
            the status were not available.*/
        //Available now only
        else if (isDoctorAvailableNow && layout.getChildCount() < 1) {

            horizontalscrollview.setVisibility(View.GONE);
            findViewById(R.id.dateTxtLayout).setVisibility(View.GONE);
            if (str_Availability_Type.equalsIgnoreCase("video")) {
                onlyVideo();

            } else if (str_Availability_Type.equalsIgnoreCase("video or phone")) {
                VideoOrPhoneNotAvailable();
            } else if (str_Availability_Type.equalsIgnoreCase("phone")) {
                onlyPhone();
            } else if (str_Availability_Type.equalsIgnoreCase("With Patient")) {
                onlyWithPatient();
            }

        }

        //Available now and later
        //Part1 ----> timeslot zero followed by many timeslots
        else if (isDoctorAvailableNow && layout.getChildCount() >= 1) {
            enableOrdisableProviderDetails(str_Availability_Type);

        }
        //part 2 available ly later
        //Part2 ----> timeslot not zero followed by many timeslots
        else if (!isDoctorAvailableNow && layout.getChildCount() >= 1) {
            availableOnlyLater(str_Availability_Type);

        }

        //not available

        else if (layout.getChildCount() == 0 && str_Availability_Type.equals("not available")) {
            if (str_appointmenttype.equals("1")) {
                notAvailable();
            } else if (str_appointmenttype.equals("2")) {
                notAvailable();
            } else {
                notAvailable();
            }
        }

        //not available
        else if (layout.getChildCount() == 0) {
            horizontalscrollview.setVisibility(View.GONE);
            findViewById(R.id.dateTxtLayout).setVisibility(View.GONE);
            if (str_Availability_Type.equalsIgnoreCase("video")) {
                onlyVideo();

            } else if (str_Availability_Type.equalsIgnoreCase("video or phone")) {
                VideoOrPhoneNotAvailable();
            } else if (str_Availability_Type.equalsIgnoreCase("phone")) {
                onlyPhone();
            } else if (str_Availability_Type.equalsIgnoreCase("With patient")) {
                onlyWithPatient();
            } else if (str_Availability_Type.equalsIgnoreCase("not available")) {
                //Make future appointment only
                notAvailable();
            }
        }

        setResponseQualificationDetails(providerdetObj, str_Availability_Type);

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.nest5.businessClient.Initialactivity.java

@Override
public void OnHomeObjectFragmentCreated(View v) {
    // TODO Auto-generated method stub
    LinearLayout ll = (LinearLayout) v.findViewById(R.id.ingredient_categories_buttons);
    ll.removeAllViews();
    String values[] = { "Combos", "Productos", "Ingredientes", "+Vendido", "Nuevo" };

    for (int i = 0; i < values.length; i++) {

        Button btnTag = (Button) getLayoutInflater().inflate(R.layout.template_button, null);
        btnTag.setText((values[i]));//from   w ww .  j a va2s  . c om
        btnTag.setId(i);
        btnTag.setOnClickListener(typeButtonClickListener);
        ll.addView(btnTag);

    }
    SharedPreferences defaultprefs = PreferenceManager.getDefaultSharedPreferences(mContext);
    boolean layouttables = defaultprefs.getBoolean("arrange_tables", false);

    itemsView = (GridView) v.findViewById(R.id.gridview);
    statusText = (TextView) v.findViewById(R.id.group_owner);
    deviceText = (TextView) v.findViewById(R.id.device_info);
    saleValue = (TextView) v.findViewById(R.id.sale_info);
    autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autocomplete_registrable);
    if (layouttables) {
        statusText.setVisibility(View.VISIBLE);
        //statusText.setText("No hay Mesa Seleccionada.");
    } else {
        statusText.setVisibility(View.INVISIBLE);
        statusText.setText("");
    }
    updateSaleValue();
    pagarButton = (Button) v.findViewById(R.id.pay_register);
    guardarButton = (Button) v.findViewById(R.id.save_register);
    pagarButton.setOnClickListener(payListener);
    guardarButton.setOnClickListener(saveListener);
    registerList = new ArrayList<Registrable>();
    gridAdapter = new ImageAdapter(mContext, registerList, inflater, gridButtonListener);
    setGridContent(gridAdapter, comboList);
    ArrayList<String> registrables = new ArrayList<String>();
    for (Registrable actual : allRegistrables) {
        registrables.add(actual.name);
    }
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, registrables);
    autoCompleteTextView.setAdapter(adapter);
    autoCompleteTextView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            String selection = (String) parent.getItemAtPosition(position);
            int pos = -1;

            for (int i = 0; i < allRegistrables.size(); i++) {
                if (allRegistrables.get(i).name.equalsIgnoreCase(selection)) {
                    pos = i;
                    break;
                }
            }
            if (pos > -1) {
                if (currentOrder.containsKey(allRegistrables.get(pos))) {
                    currentOrder.put(allRegistrables.get(pos), currentOrder.get(allRegistrables.get(pos)) + 1);

                } else {
                    currentOrder.put(allRegistrables.get(pos), 1);
                }
                makeTable(allRegistrables.get(pos).name);
            } else {
                Toast.makeText(mContext, "No Existe el tem", Toast.LENGTH_LONG).show();
            }
            autoCompleteTextView.setText("");
            autoCompleteTextView.setHint("Buscar tems para Registrar");

        }

    });
    autoCompleteTextView.setText("");
    autoCompleteTextView.setHint("Buscar tems para Registrar");
    // Tomar la tabla de la izquierda del home view
    table = (TableLayout) v.findViewById(R.id.my_table);
    makeTable("NA");

    deviceText.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mTCPPrint != null) {
                mTCPPrint.stopClient();
            }
            new connectTask().execute("");

        }
    });

}

From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

private void createSearchDialog() {
    final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_search_tools,
            R.string.search_tools_title);

    final ScrollView scrollView = (ScrollView) dialog.findViewById(R.id.search_tools_dialog_scroll_view);
    final AutoCompleteTextView inputField = (AutoCompleteTextView) dialog
            .findViewById(R.id.search_tools_input_field);
    final LinearLayout rowsContainer = (LinearLayout) dialog.findViewById(R.id.search_tools_row_container);
    final Button viewInMapButton = (Button) dialog.findViewById(R.id.search_tools_view_in_map_button);
    final Button jumpToBottomButton = (Button) dialog.findViewById(R.id.search_tools_jump_to_bottom_button);
    Button dismissButton = (Button) dialog.findViewById(R.id.search_tools_dismiss_button);

    List<PropertyDescription> subscribables;
    PropertyDescription newestSubscribable = null;
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",
            Locale.getDefault());
    Date cachedUpdateDateTime;//from   ww w  .ja v a  2  s.c o  m
    Date newestUpdateDateTime;
    SubscriptionEntry cachedEntry;
    Response response;
    final JSONArray toolsArray;
    ArrayAdapter<String> adapter;
    String format = "JSON";
    String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .toString() + "/FiskInfo/Offline/";
    final JSONObject tools;
    final List<String> vesselNames;
    final Map<String, List<Integer>> toolIdMap = new HashMap<>();
    byte[] data = new byte[0];

    cachedEntry = user.getSubscriptionCacheEntry(getString(R.string.fishing_facility_api_name));

    if (fiskInfoUtility.isNetworkAvailable(getActivity())) {
        subscribables = barentswatchApi.getApi().getSubscribable();
        for (PropertyDescription subscribable : subscribables) {
            if (subscribable.ApiName.equals(getString(R.string.fishing_facility_api_name))) {
                newestSubscribable = subscribable;
                break;
            }
        }
    } else if (cachedEntry == null) {
        Dialog infoDialog = dialogInterface.getAlertDialog(getActivity(), R.string.tools_search_no_data_title,
                R.string.tools_search_no_data, -1);

        infoDialog.show();
        return;
    }

    if (cachedEntry != null) {
        try {
            cachedUpdateDateTime = simpleDateFormat
                    .parse(cachedEntry.mLastUpdated.equals(getActivity().getString(R.string.abbreviation_na))
                            ? "2000-00-00T00:00:00"
                            : cachedEntry.mLastUpdated);
            newestUpdateDateTime = simpleDateFormat
                    .parse(newestSubscribable != null ? newestSubscribable.LastUpdated : "2000-00-00T00:00:00");

            if (cachedUpdateDateTime.getTime() - newestUpdateDateTime.getTime() < 0) {
                response = barentswatchApi.getApi().geoDataDownload(newestSubscribable.ApiName, format);
                try {
                    data = FiskInfoUtility.toByteArray(response.getBody().in());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (new FiskInfoUtility().writeMapLayerToExternalStorage(getActivity(), data,
                        newestSubscribable.Name.replace(",", "").replace(" ", "_"), format, downloadPath,
                        false)) {
                    SubscriptionEntry entry = new SubscriptionEntry(newestSubscribable, true);
                    entry.mLastUpdated = newestSubscribable.LastUpdated;
                    user.setSubscriptionCacheEntry(newestSubscribable.ApiName, entry);
                    user.writeToSharedPref(getActivity());
                }
            } else {
                String directoryFilePath = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
                        + "/FiskInfo/Offline/";

                File file = new File(directoryFilePath + newestSubscribable.Name + ".JSON");
                StringBuilder jsonString = new StringBuilder();
                BufferedReader bufferReader = null;

                try {
                    bufferReader = new BufferedReader(new FileReader(file));
                    String line;

                    while ((line = bufferReader.readLine()) != null) {
                        jsonString.append(line);
                        jsonString.append('\n');
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (bufferReader != null) {
                        try {
                            bufferReader.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                data = jsonString.toString().getBytes();
            }

        } catch (ParseException e) {
            e.printStackTrace();
            Log.e(TAG, "Invalid datetime provided");
        }
    } else {
        response = barentswatchApi.getApi().geoDataDownload(newestSubscribable.ApiName, format);
        try {
            data = FiskInfoUtility.toByteArray(response.getBody().in());
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (new FiskInfoUtility().writeMapLayerToExternalStorage(getActivity(), data,
                newestSubscribable.Name.replace(",", "").replace(" ", "_"), format, downloadPath, false)) {
            SubscriptionEntry entry = new SubscriptionEntry(newestSubscribable, true);
            entry.mLastUpdated = newestSubscribable.LastUpdated;
            user.setSubscriptionCacheEntry(newestSubscribable.ApiName, entry);
        }
    }

    try {
        tools = new JSONObject(new String(data));
        toolsArray = tools.getJSONArray("features");
        vesselNames = new ArrayList<>();
        adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, vesselNames);

        for (int i = 0; i < toolsArray.length(); i++) {
            JSONObject feature = toolsArray.getJSONObject(i);
            String vesselName = (feature.getJSONObject("properties").getString("vesselname") != null
                    && !feature.getJSONObject("properties").getString("vesselname").equals("null"))
                            ? feature.getJSONObject("properties").getString("vesselname")
                            : getString(R.string.vessel_name_unknown);
            List<Integer> toolsIdList = toolIdMap.get(vesselName) != null ? toolIdMap.get(vesselName)
                    : new ArrayList<Integer>();

            if (vesselName != null && !vesselNames.contains(vesselName)) {
                vesselNames.add(vesselName);
            }

            toolsIdList.add(i);
            toolIdMap.put(vesselName, toolsIdList);
        }

        inputField.setAdapter(adapter);
    } catch (JSONException e) {
        dialogInterface.getAlertDialog(getActivity(), R.string.search_tools_init_error,
                R.string.search_tools_init_info, -1).show();
        Log.e(TAG, "JSON parse error");
        e.printStackTrace();

        return;
    }

    if (searchToolsButton.getTag() != null) {
        inputField.requestFocus();
        inputField.setText(searchToolsButton.getTag().toString());
        inputField.selectAll();
    }

    inputField.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String selectedVesselName = ((TextView) view).getText().toString();
            List<Integer> selectedTools = toolIdMap.get(selectedVesselName);
            Gson gson = new Gson();
            String toolSetDateString;
            Date toolSetDate;

            rowsContainer.removeAllViews();

            for (int toolId : selectedTools) {
                JSONObject feature;
                Feature toolFeature;

                try {
                    feature = toolsArray.getJSONObject(toolId);

                    if (feature.getJSONObject("geometry").getString("type").equals("LineString")) {
                        toolFeature = gson.fromJson(feature.toString(), LineFeature.class);
                    } else {
                        toolFeature = gson.fromJson(feature.toString(), PointFeature.class);
                    }

                    toolSetDateString = toolFeature.properties.setupdatetime != null
                            ? toolFeature.properties.setupdatetime
                            : "2038-00-00T00:00:00";
                    toolSetDate = simpleDateFormat.parse(toolSetDateString);

                } catch (JSONException | ParseException e) {
                    dialogInterface.getAlertDialog(getActivity(), R.string.search_tools_init_error,
                            R.string.search_tools_init_info, -1).show();
                    e.printStackTrace();

                    return;
                }

                ToolSearchResultRow row = rowsInterface.getToolSearchResultRow(getActivity(),
                        R.drawable.ikon_kystfiske, toolFeature);
                long toolTime = System.currentTimeMillis() - toolSetDate.getTime();
                long highlightCutoff = ((long) getResources().getInteger(R.integer.milliseconds_in_a_day))
                        * ((long) getResources().getInteger(R.integer.days_to_highlight_active_tool));

                if (toolTime > highlightCutoff) {
                    int colorId = ContextCompat.getColor(getActivity(), R.color.error_red);
                    row.setDateTextViewTextColor(colorId);
                }

                rowsContainer.addView(row.getView());
            }

            viewInMapButton.setEnabled(true);
            inputField.setTag(selectedVesselName);
            searchToolsButton.setTag(selectedVesselName);
            jumpToBottomButton.setVisibility(View.VISIBLE);
            jumpToBottomButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.scrollTo(0, rowsContainer.getBottom());
                        }
                    });
                }
            });

        }
    });

    viewInMapButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String vesselName = inputField.getTag().toString();
            highlightToolsInMap(vesselName);

            dialog.dismiss();
        }
    });

    dismissButton.setOnClickListener(onClickListenerInterface.getDismissDialogListener(dialog));
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    dialog.show();
}