Example usage for android.widget ScrollView scrollTo

List of usage examples for android.widget ScrollView scrollTo

Introduction

In this page you can find the example usage for android.widget ScrollView scrollTo.

Prototype

@Override
public void scrollTo(int x, int y) 

Source Link

Document

This version also clamps the scrolling to the bounds of our child.

Usage

From source file:org.libreoffice.impressremote.fragment.slides.SlidesPagerFragment.java

private void scrollSlideNotes() {
    ScrollView aSlideNotesScroll = (ScrollView) getView().findViewById(R.id.scroll_notes);

    aSlideNotesScroll.scrollTo(0, 0);
}

From source file:de.uulm.graphicalpasswords.openuyi.UYICreatePasswordActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_uyi_create_password);
    // Show the Up button in the action bar.
    setupActionBar();//from   w  w  w.  j a v  a  2s .  c om

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    length = Integer.parseInt(sharedPref.getString("uyi_length", "10"));

    originalViews = new ImageView[length];
    distortedViews = new ImageView[length];
    selectedPictures = new Picture[length];

    Bundle bundle = new Bundle();
    bundle.putInt("length", length);
    DialogFragment intro = new IntroDialogFragment();
    intro.setArguments(bundle);
    intro.show(getFragmentManager(), "intro");

    vibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);

    Arrays.fill(selectedPictures, null);

    gallery = (Gallery) findViewById(R.id.uyi_gallery_originals);
    gallery.setAdapter(new UYIImageAdapter(this));

    gallery.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            ImageView viewOriginal = new ImageView(UYICreatePasswordActivity.this);
            ImageView viewDistorted = new ImageView(UYICreatePasswordActivity.this);

            int i = 0;
            for (; i < selectedPictures.length; i++) {
                if (i == selectedPictures.length - 1 && selectedPictures[i] != null) {
                    removePicture(i);
                }
                if (selectedPictures[i] == null || i == selectedPictures.length - 1) {
                    viewOriginal = originalViews[i];
                    viewDistorted = distortedViews[i];
                    selectedPictures[i] = ((UYIImageAdapter) parent.getAdapter()).getPicture(position);
                    vibrator.vibrate(100);

                    ScrollView sv = (ScrollView) findViewById(R.id.uyi_choosepi_scrollview);
                    int height = originalViews[0].getMeasuredHeight();
                    sv.scrollTo(0, (i * height) - 200);

                    break;
                }
            }

            int originalImageResource = ((UYIImageAdapter) parent.getAdapter()).getImageResource(position);
            viewOriginal.setImageResource(originalImageResource);
            viewDistorted.setImageResource(
                    ((UYIImageAdapter) parent.getAdapter()).getDistortedImageResource(position));
            ((UYIImageAdapter) parent.getAdapter()).removePicture(position);

            OnLongClickListener listener = new OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    vibrator.vibrate(200);
                    int viewid = v.getId();
                    int index = -1;

                    for (int i = 0; i < originalViews.length; i++) {
                        if (originalViews[i].getId() == viewid) {
                            index = i;
                            break;
                        } else if (distortedViews[i].getId() == viewid) {
                            index = i;
                            break;
                        }
                    }
                    Bundle bundle = new Bundle();
                    bundle.putInt("index", index);
                    DialogFragment dialog = new DeleteImageDialogFragment();
                    dialog.setArguments(bundle);
                    dialog.show(getFragmentManager(), "delete");
                    return false;
                }
            };

            viewOriginal.setOnLongClickListener(listener);
            viewDistorted.setOnLongClickListener(listener);

            // Check
            int count = 0;
            for (int j = 0; j < selectedPictures.length; j++) {
                if (selectedPictures[j] != null) {
                    count++;
                }
            }
            if (count == selectedPictures.length) {
                findViewById(R.id.uyi_save).setClickable(true);
                findViewById(R.id.uyi_save).setEnabled(true);
            }
        }
    });

    table = (TableLayout) findViewById(R.id.uyi_choosepi_tablelayout);
    LayoutParams params = new LayoutParams(android.widget.TableRow.LayoutParams.WRAP_CONTENT,
            android.widget.TableRow.LayoutParams.WRAP_CONTENT);
    params.gravity = Gravity.CENTER;
    for (int i = 0; i < length; i++) {
        TableRow row = new TableRow(table.getContext());

        originalViews[i] = new ImageView(row.getContext());
        originalViews[i].setAdjustViewBounds(true);
        originalViews[i].setScaleType(ScaleType.FIT_XY);
        originalViews[i].setPadding(3, 3, 3, 3);
        originalViews[i].setImageResource(R.drawable.oempty);
        originalViews[i].setId(100 + i);

        distortedViews[i] = new ImageView(row.getContext());
        distortedViews[i].setAdjustViewBounds(true);
        distortedViews[i].setScaleType(ScaleType.FIT_XY);
        distortedViews[i].setPadding(3, 3, 3, 3);
        distortedViews[i].setImageResource(R.drawable.wempty);
        distortedViews[i].setId(1000 + i);

        ImageView arrow = new ImageView(row.getContext());
        arrow.setAdjustViewBounds(true);
        arrow.setScaleType(ScaleType.FIT_XY);
        arrow.setMaxWidth(80);
        arrow.setPadding(3, 3, 3, 3);
        arrow.setImageResource(R.drawable.arrow_active);
        arrow.setLayoutParams(params);

        row.addView(originalViews[i]);
        row.addView(arrow);
        row.addView(distortedViews[i]);
        table.addView(row);
    }
}

From source file:com.cerema.cloud2.ui.fragment.ShareFileFragment.java

private void updateListOfUserGroups() {
    // Update list of users/groups
    // TODO Refactoring: create a new {@link ShareUserListAdapter} instance with every call should not be needed
    mUserGroupsAdapter = new ShareUserListAdapter(getActivity(), R.layout.share_user_item, mPrivateShares,
            this);

    // Show data// w w w. j a v  a  2s  .c om
    TextView noShares = (TextView) getView().findViewById(R.id.shareNoUsers);
    ListView usersList = (ListView) getView().findViewById(R.id.shareUsersList);

    if (mPrivateShares.size() > 0) {
        noShares.setVisibility(View.GONE);
        usersList.setVisibility(View.VISIBLE);
        usersList.setAdapter(mUserGroupsAdapter);
        setListViewHeightBasedOnChildren(usersList);
    } else {
        noShares.setVisibility(View.VISIBLE);
        usersList.setVisibility(View.GONE);
    }

    // Set Scroll to initial position
    ScrollView scrollView = (ScrollView) getView().findViewById(R.id.shareScroll);
    scrollView.scrollTo(0, 0);
}

From source file:au.org.ala.fielddata.mobile.CollectSurveyData.java

public void scrollTo(final Attribute attribute) {
    pager.post(new Runnable() {
        public void run() {

            Binder binder = (Binder) surveyViewModel.getAttributeListener(attribute);
            View boundView = binder.getView();
            ViewParent parent = boundView.getParent();
            while (parent != null && !(parent instanceof ScrollView)) {
                parent = parent.getParent();
            }/*from  w  w w  .j  av a  2  s.  c  o  m*/

            if (parent != null) {
                final ScrollView view = (ScrollView) parent;
                final Rect r = new Rect();

                view.offsetDescendantRectToMyCoords((View) boundView.getParent(), r);
                view.post(new Runnable() {
                    public void run() {
                        view.scrollTo(0, r.bottom);
                    }
                });

            }
        }
    });
}

From source file:gr.scify.newsum.ui.SearchViewActivity.java

private void initTopicSpinner() {
    // Get topics in category. Null accepts all user sources. Modify
    // according to user selection
    final String[] saTopicIDs = SearchTopicActivity.saTopicIDs;
    final String[] saTitles = SearchTopicActivity.saTopicTitles;
    final String[] saDates = SearchTopicActivity.saTopicDates;
    // TODO add TopicInfo for SearchResults as well and parse accordingly

    // final String[] saTopicIDs = extras.getStringArray("searchresults");
    final TextView title = (TextView) findViewById(R.id.title);
    // Fill topic spinner
    ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,
            android.R.layout.simple_spinner_item, saTitles);

    final TextView tx = (TextView) findViewById(R.id.textView1);
    // tx.setMovementMethod(LinkMovementMethod.getInstance());
    //      final float minm = tx.getTextSize();
    //      final float maxm = (minm + 24);

    // create an invisible spinner just to control the summaries of the
    // category (i will use it later on Swipe)
    Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);//from  w  ww . j  a va  2 s  . c o  m

    // Scroll view init
    final ScrollView scroll = (ScrollView) findViewById(R.id.scrollView1);
    // Add selection event
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            // Show waiting dialog
            showWaitingDialog();

            // Changing summary
            loading = true;
            // Update visibility of rating bar
            final RatingBar rb = (RatingBar) findViewById(R.id.ratingBar);
            rb.setRating(0.0f);
            rb.setVisibility(View.VISIBLE);
            final TextView rateLbl = (TextView) findViewById(R.id.rateLbl);
            rateLbl.setVisibility(View.VISIBLE);

            scroll.scrollTo(0, 0);
            //            String[] saTopicIDs = sTopicIds.split(sSeparator);

            SharedPreferences settings = getSharedPreferences("urls", 0);
            // get user settings for sources
            String UserSources = settings.getString("UserLinks", "All");
            String[] Summary = NewSumServiceClient.getSummary(saTopicIDs[arg2], UserSources);
            if (Summary.length == 0) { // WORK. Updated: CHECK
                // Close waiting dialog
                closeWaitingDialog();

                AlertDialog.Builder alert = new AlertDialog.Builder(SearchViewActivity.this);
                alert.setMessage(R.string.shouldReloadSummaries);
                alert.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        startActivity(new Intent(getApplicationContext(), NewSumUiActivity.class)
                                .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                    }
                });
                alert.setCancelable(false);
                alert.show();
                loading = false;
                return;
            }
            // track summary views per Search and topic title
            if (getAnalyticsPref()) {
                EasyTracker.getTracker().sendEvent(VIEW_SUMMARY_ACTION, "From Search",
                        saTitles[arg2] + ": " + saDates[arg2], 0l);
            }
            // Generate summary text
            sText = ViewActivity.generateSummaryText(Summary, SearchViewActivity.this);
            pText = ViewActivity.generatesummarypost(Summary, SearchViewActivity.this);
            tx.setText(Html.fromHtml(sText));
            tx.setMovementMethod(LinkMovementMethod.getInstance());
            title.setText(saTitles[arg2] + ": " + saDates[arg2]);
            float defSize = tx.getTextSize();
            SharedPreferences usersize = getSharedPreferences("textS", 0);
            float newSize = usersize.getFloat("size", defSize);
            tx.setTextSize(TypedValue.COMPLEX_UNIT_PX, newSize);
            // update the TopicActivity with viewed item
            TopicActivity.addVisitedTopicID(saTopicIDs[arg2]);

            // Close waiting dialog
            closeWaitingDialog();

        }

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

    });

}

From source file:gr.scify.newsum.ui.ViewActivity.java

@Override
public void run() {
    // take the String from the TopicActivity
    Bundle extras = getIntent().getExtras();
    Category = extras.getString(CATEGORY_INTENT_VAR);

    // Make sure we have updated the data source
    NewSumUiActivity.setDataSource(this);

    // Get user sources
    String sUserSources = Urls.getUserVisibleURLsAsString(ViewActivity.this);

    // get Topics from TopicActivity (avoid multiple server calls)
    TopicInfo[] tiTopics = TopicActivity.getTopics(sUserSources, Category, this);

    // Also get Topic Titles, to display to adapter
    final String[] saTopicTitles = new String[tiTopics.length];
    // Also get Topic IDs
    final String[] saTopicIDs = new String[tiTopics.length];
    // Also get Dates, in order to show in summary title
    final String[] saTopicDates = new String[tiTopics.length];
    // DeHTML titles
    for (int iCnt = 0; iCnt < tiTopics.length; iCnt++) {
        // update Titles Array
        saTopicTitles[iCnt] = Html.fromHtml(tiTopics[iCnt].getTitle()).toString();
        // update IDs Array
        saTopicIDs[iCnt] = tiTopics[iCnt].getID();
        // update Date Array
        saTopicDates[iCnt] = tiTopics[iCnt].getPrintableDate(NewSumUiActivity.getDefaultLocale());
    }//from  w  ww.  j a va2 s. co  m
    // get the value of the TopicIDs list size (to use in swipe)
    saTopicIDsLength = saTopicIDs.length;
    final TextView title = (TextView) findViewById(R.id.title);
    // Fill topic spinner
    final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,
            android.R.layout.simple_spinner_item, saTopicTitles);

    final TextView tx = (TextView) findViewById(R.id.textView1);
    //      final float minm = tx.getTextSize();
    //      final float maxm = (minm + 24);

    // Get active topic
    int iTopicNum;
    // If we have returned from a pause
    if (iPrvSelectedItem >= 0)
        // use previous selection before pause
        iTopicNum = iPrvSelectedItem;
    // else
    else
        // use selection from topic page
        iTopicNum = extras.getInt(TOPIC_ID_INTENT_VAR);
    final int num = iTopicNum;

    // create an invisible spinner just to control the summaries of the
    // category (i will use it later on Swipe)
    final Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            spinner.setAdapter(adapter);

            // Scroll view init
            final ScrollView scroll = (ScrollView) findViewById(R.id.scrollView1);
            final String[] saTopicTitlesArg = saTopicTitles;
            final String[] saTopicIDsArg = saTopicIDs;
            final String[] SaTopicDatesArg = saTopicDates;

            // Add selection event
            spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                    // Changing summary
                    loading = true;
                    showWaitingDialog();
                    // Update visibility of rating bar
                    final RatingBar rb = (RatingBar) findViewById(R.id.ratingBar);
                    rb.setRating(0.0f);
                    rb.setVisibility(View.VISIBLE);
                    final TextView rateLbl = (TextView) findViewById(R.id.rateLbl);
                    rateLbl.setVisibility(View.VISIBLE);
                    scroll.scrollTo(0, 0);

                    String UserSources = Urls.getUserVisibleURLsAsString(ViewActivity.this);

                    String[] saTopicIDs = saTopicIDsArg;

                    // track summary views per category and topic title
                    if (getAnalyticsPref()) {
                        EasyTracker.getTracker().sendEvent(VIEW_SUMMARY_ACTION, Category,
                                saTopicTitlesArg[arg2], 0l);
                    }

                    if (sCustomCategory.trim().length() > 0) {
                        if (Category.equals(sCustomCategory)) {
                            Context ctxCur = NewSumUiActivity.getAppContext(ViewActivity.this);
                            String sCustomCategoryURL = ctxCur.getResources()
                                    .getString(R.string.custom_category_url);
                            // Check if specific element needs to be read
                            String sElementID = ctxCur.getResources()
                                    .getString(R.string.custom_category_elementId);
                            // If an element needs to be selected
                            if (sElementID.trim().length() > 0) {
                                try {
                                    // Check if specific element needs to be read
                                    String sViewOriginalPage = ctxCur.getResources()
                                            .getString(R.string.custom_category_visit_source);
                                    // Init text by a link to the original page
                                    sText = "<p><a href='" + sCustomCategoryURL + "'>" + sViewOriginalPage
                                            + "</a></p>";
                                    // Get document
                                    Document doc = Jsoup.connect(sCustomCategoryURL).get();
                                    // If a table
                                    Element eCur = doc.getElementById(sElementID);
                                    if (eCur.tagName().equalsIgnoreCase("table")) {
                                        // Get table rows
                                        Elements eRows = eCur.select("tr");

                                        // For each row
                                        StringBuffer sTextBuf = new StringBuffer();
                                        for (Element eCurRow : eRows) {
                                            // Append content
                                            // TODO: Use HTML if possible. Now problematic (crashes when we click on link)
                                            sTextBuf.append("<p>" + eCurRow.text() + "</p>");
                                        }
                                        // Return as string
                                        sText = sText + sTextBuf.toString();
                                    } else
                                        // else get text
                                        sText = eCur.text();

                                } catch (IOException e) {
                                    // Show unavailable text
                                    sText = ctxCur.getResources()
                                            .getString(R.string.custom_category_unavailable);
                                    e.printStackTrace();
                                }

                            } else
                                sText = Utils.getFromHttp(sCustomCategoryURL, false);
                        }

                    } else {
                        // call getSummary with (sTopicID, sUserSources). Use "All" for
                        // all Sources
                        String[] Summary = NewSumServiceClient.getSummary(saTopicIDs[arg2], UserSources);
                        // check if Summary exists, otherwise display message
                        if (Summary.length == 0) { // DONE APPLICATION HANGS, DOES NOT
                            // WORK. Updated: Probably OK
                            nothingFound = true;
                            AlertDialog.Builder al = new AlertDialog.Builder(ViewActivity.this);
                            al.setMessage(R.string.shouldReloadSummaries);
                            al.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface arg0, int arg1) {
                                    // Reset cache
                                    CacheController.clearCache();
                                    // Restart main activity
                                    startActivity(new Intent(getApplicationContext(), NewSumUiActivity.class)
                                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                                }
                            });
                            al.setCancelable(false);
                            al.show();
                            // Return to home activity
                            loading = false;
                            return;
                        }
                        // Generate Summary text for normal categories
                        sText = generateSummaryText(Summary, ViewActivity.this);
                        pText = generatesummarypost(Summary, ViewActivity.this);
                    }

                    // Update HTML
                    tx.setText(Html.fromHtml(sText));
                    // Allow links to be followed into browser
                    tx.setMovementMethod(LinkMovementMethod.getInstance());
                    // Also Add Date to Topic Title inside Summary
                    title.setText(saTopicTitlesArg[arg2] + " : " + SaTopicDatesArg[arg2]);

                    // Update size
                    updateTextSize();

                    // Update visited topics
                    TopicActivity.addVisitedTopicID(saTopicIDs[arg2]);
                    // Done
                    loading = false;
                    closeWaitingDialog();
                }

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

            });

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // Get active topic
                    spinner.setSelection(num);
                }
            });

        }
    });

    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            showHelpDialog();
        }
    });

    closeWaitingDialog();
}

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. j  a v a 2  s .  co  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();
}