List of usage examples for android.widget AutoCompleteTextView setAdapter
public <T extends ListAdapter & Filterable> void setAdapter(T adapter)
Changes the list of data used for auto completion.
From source file:com.owncloud.android.ui.adapter.FileListListAdapter.java
@Override public View getView(final int position, View convertView, ViewGroup parent) { View view = convertView;// w w w .j av a 2 s .c om if (view == null) { LayoutInflater inflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflator.inflate(R.layout.list_item, null); } if (mFiles != null && mFiles.size() > position) { OCFile file = mFiles.get(position); TextView fileName = (TextView) view.findViewById(R.id.Filename); String name = file.getFileName(); if (dataSourceShareFile == null) dataSourceShareFile = new DbShareFile(mContext); Account account = AccountUtils.getCurrentOwnCloudAccount(mContext); String[] accountNames = account.name.split("@"); if (accountNames.length > 2) { accountName = accountNames[0] + "@" + accountNames[1]; url = accountNames[2]; } Map<String, String> fileSharers = dataSourceShareFile.getUsersWhoSharedFilesWithMe(accountName); TextView sharer = (TextView) view.findViewById(R.id.sharer); ImageView shareButton = (ImageView) view.findViewById(R.id.shareItem); fileName.setText(name); ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1); fileIcon.setImageResource(DisplayUtils.getResourceId(file.getMimetype())); ImageView localStateView = (ImageView) view.findViewById(R.id.imageView2); FileDownloaderBinder downloaderBinder = mTransferServiceGetter.getFileDownloaderBinder(); FileUploaderBinder uploaderBinder = mTransferServiceGetter.getFileUploaderBinder(); if (fileSharers.size() != 0 && (!file.equals("Shared") && file.getRemotePath().contains("Shared"))) { if (fileSharers.containsKey(name)) { sharer.setText(fileSharers.get(name)); fileSharers.remove(name); } else { sharer.setText(" "); } } else { sharer.setText(" "); } if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file)) { localStateView.setImageResource(R.drawable.downloading_file_indicator); localStateView.setVisibility(View.VISIBLE); } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file)) { localStateView.setImageResource(R.drawable.uploading_file_indicator); localStateView.setVisibility(View.VISIBLE); } else if (file.isDown()) { localStateView.setImageResource(R.drawable.local_file_indicator); localStateView.setVisibility(View.VISIBLE); } else { localStateView.setVisibility(View.INVISIBLE); } TextView fileSizeV = (TextView) view.findViewById(R.id.file_size); TextView lastModV = (TextView) view.findViewById(R.id.last_mod); ImageView checkBoxV = (ImageView) view.findViewById(R.id.custom_checkbox); shareButton.setOnClickListener(new OnClickListener() { String shareStatusDisplay; int flagShare = 0; @Override public void onClick(View v) { final Dialog dialog = new Dialog(mContext); final OCFile fileToBeShared = (OCFile) getItem(position); final ArrayAdapter<String> shareWithFriends; final ArrayAdapter<String> shareAdapter; final String filePath; sharedWith = new ArrayList<String>(); dataSource = new DbFriends(mContext); dataSourceShareFile = new DbShareFile(mContext); dialog.setContentView(R.layout.share_file_with); dialog.setTitle("Share"); Account account = AccountUtils.getCurrentOwnCloudAccount(mContext); String[] accountNames = account.name.split("@"); if (accountNames.length > 2) { accountName = accountNames[0] + "@" + accountNames[1]; url = accountNames[2]; } final AutoCompleteTextView textView = (AutoCompleteTextView) dialog .findViewById(R.id.autocompleteshare); Button shareBtn = (Button) dialog.findViewById(R.id.ShareBtn); Button doneBtn = (Button) dialog.findViewById(R.id.ShareDoneBtn); final ListView listview = (ListView) dialog.findViewById(R.id.alreadySharedWithList); textView.setThreshold(2); final String itemType; filePath = "files" + String.valueOf(fileToBeShared.getRemotePath()); final String fileName = fileToBeShared.getFileName(); final String fileRemotePath = fileToBeShared.getRemotePath(); if (dataSourceShareFile == null) dataSourceShareFile = new DbShareFile(mContext); sharedWith = dataSourceShareFile.getUsersWithWhomIhaveSharedFile(fileName, fileRemotePath, accountName, String.valueOf(1)); shareAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, sharedWith); listview.setAdapter(shareAdapter); final String itemSource; if (fileToBeShared.isDirectory()) { itemType = "folder"; int lastSlashInFolderPath = filePath.lastIndexOf('/'); itemSource = filePath.substring(0, lastSlashInFolderPath); } else { itemType = "file"; itemSource = filePath; } //Permissions disabled with friends app ArrayList<String> friendList = dataSource.getFriendList(accountName); dataSource.close(); shareWithFriends = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, friendList); textView.setAdapter(shareWithFriends); textView.setFocusableInTouchMode(true); dialog.show(); textView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { } }); final Handler finishedHandler = new Handler() { @Override public void handleMessage(Message msg) { shareAdapter.notifyDataSetChanged(); Toast.makeText(mContext, shareStatusDisplay, Toast.LENGTH_SHORT).show(); } }; shareBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final String shareWith = textView.getText().toString(); if (shareWith.equals("")) { textView.setHint("Share With"); Toast.makeText(mContext, "Please enter the friends name with whom you want to share", Toast.LENGTH_SHORT).show(); } else if (sharedWith.contains(shareWith)) { textView.setHint("Share With"); Toast.makeText(mContext, "You have shared the file with that person", Toast.LENGTH_SHORT).show(); } else { textView.setText(""); Runnable runnable = new Runnable() { @Override public void run() { HttpPost post = new HttpPost( "http://" + url + "/owncloud/androidshare.php"); final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("itemType", itemType)); params.add(new BasicNameValuePair("itemSource", itemSource)); params.add(new BasicNameValuePair("shareType", shareType)); params.add(new BasicNameValuePair("shareWith", shareWith)); params.add(new BasicNameValuePair("permission", permissions)); params.add(new BasicNameValuePair("uidOwner", accountName)); HttpEntity entity; String shareSuccess = "false"; try { entity = new UrlEncodedFormEntity(params, "utf-8"); HttpClient client = new DefaultHttpClient(); post.setEntity(entity); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entityresponse = response.getEntity(); String jsonentity = EntityUtils.toString(entityresponse); JSONObject obj = new JSONObject(jsonentity); shareSuccess = obj.getString("SHARE_STATUS"); flagShare = 1; if (shareSuccess.equals("true")) { dataSourceShareFile.putNewShares(fileName, fileRemotePath, accountName, shareWith); sharedWith.add(shareWith); shareStatusDisplay = "File share succeeded"; } else if (shareSuccess.equals("INVALID_FILE")) { shareStatusDisplay = "File you are trying to share does not exist"; } else if (shareSuccess.equals("INVALID_SHARETYPE")) { shareStatusDisplay = "File Share type is invalid"; } else { shareStatusDisplay = "Share did not succeed. Please check your internet connection"; } finishedHandler.sendEmptyMessage(flagShare); } } catch (Exception e) { e.printStackTrace(); } } }; new Thread(runnable).start(); } if (flagShare == 1) { } } }); doneBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); //dataSourceShareFile.close(); } }); } }); //dataSourceShareFile.close(); if (!file.isDirectory()) { fileSizeV.setVisibility(View.VISIBLE); fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength())); lastModV.setVisibility(View.VISIBLE); lastModV.setText(DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp())); // this if-else is needed even thoe fav icon is visible by default // because android reuses views in listview if (!file.keepInSync()) { view.findViewById(R.id.imageView3).setVisibility(View.GONE); } else { view.findViewById(R.id.imageView3).setVisibility(View.VISIBLE); } ListView parentList = (ListView) parent; if (parentList.getChoiceMode() == ListView.CHOICE_MODE_NONE) { checkBoxV.setVisibility(View.GONE); } else { if (parentList.isItemChecked(position)) { checkBoxV.setImageResource(android.R.drawable.checkbox_on_background); } else { checkBoxV.setImageResource(android.R.drawable.checkbox_off_background); } checkBoxV.setVisibility(View.VISIBLE); } } else { fileSizeV.setVisibility(View.VISIBLE); fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength())); lastModV.setVisibility(View.VISIBLE); lastModV.setText(DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp())); checkBoxV.setVisibility(View.GONE); view.findViewById(R.id.imageView3).setVisibility(View.GONE); } } return view; }
From source file:com.httrack.android.HTTrackActivity.java
private void refreshprojectNameSuggests() { final AutoCompleteTextView name = AutoCompleteTextView.class.cast(this.findViewById(R.id.fieldProjectName)); if (name != null) { /* Setup name selection adapter. */ final String[] names = getProjectNames(); if (names != null) { Log.v(getClass().getSimpleName(), "project names: " + printArray(names)); name.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, names)); }//from ww w. ja v a 2 s .co m } }
From source file:com.dish.browser.activity.BrowserActivity.java
/** * method to generate search suggestions for the AutoCompleteTextView from * previously searched URLs/*from w w w. j a v a 2s . c o m*/ */ private void initializeSearchSuggestions(final AutoCompleteTextView getUrl) { getUrl.setThreshold(1); getUrl.setDropDownWidth(-1); getUrl.setDropDownAnchor(R.id.toolbar_layout); getUrl.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { try { String url; url = ((TextView) arg1.findViewById(R.id.url)).getText().toString(); if (url.startsWith(mActivity.getString(R.string.suggestion))) { url = ((TextView) arg1.findViewById(R.id.title)).getText().toString(); } else { getUrl.setText(url); } searchTheWeb(url); InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getUrl.getWindowToken(), 0); if (mCurrentView != null) { mCurrentView.requestFocus(); } } catch (NullPointerException e) { Log.e("Browser Error: ", "NullPointerException on item click"); } } }); getUrl.setSelectAllOnFocus(true); mSearchAdapter = new SearchAdapter(mActivity, mDarkTheme, isIncognito()); getUrl.setAdapter(mSearchAdapter); }
From source file:sms.spam.NewSmsActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_sms_layout); final AutoCompleteTextView autocompleteContact = (AutoCompleteTextView) findViewById( R.id.autocompleteContact);//from www . j a va 2 s . c o m contactsCursorAdapter = new SimpleCursorAdapter(this, R.layout.autocomplete, null, new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER }, new int[] { R.id.autocompleteText, R.id.autocompleteNumber }, 0); final ContactsLoader loader = new ContactsLoader(this); getSupportLoaderManager().initLoader(ContactsLoader.CONTACTS, null, loader); getSupportLoaderManager().initLoader(ContactsLoader.NUMBERS, null, loader); contactsCursorAdapter.setFilterQueryProvider(new FilterQueryProvider() { @Override public Cursor runQuery(final CharSequence constraint) { if (getSupportLoaderManager().hasRunningLoaders()) { return null; } return new CursorWrapper(loader.getCursor(ContactsLoader.NUMBERS)) { int pos, count; int[] indexes; { this.pos = 0; if (!constraint.equals("")) { this.indexes = new int[super.getCount()]; this.count = 0; for (int i = 0, j = 0; i < super.getCount(); ++i) { super.moveToPosition(i); if (super.getString(0).contains(constraint) || super.getString(1).contains(constraint)) { this.indexes[j++] = i; this.count++; } } } else { this.count = super.getCount(); this.indexes = new int[this.count]; for (int i = 0; i < count; ++i) { this.indexes[i] = i; } } } @Override public boolean move(int offset) { return this.moveToPosition(this.pos + offset); } @Override public boolean moveToNext() { return this.moveToPosition(this.pos + 1); } @Override public boolean moveToPrevious() { return this.moveToPosition(this.pos - 1); } @Override public boolean moveToFirst() { return this.moveToPosition(0); } @Override public boolean moveToLast() { return this.moveToPosition(this.count - 1); } @Override public boolean moveToPosition(int position) { if (position < 0 || position >= count) { return false; } this.pos = indexes[position]; return super.moveToPosition(this.pos); } @Override public int getCount() { return this.count; } @Override public int getPosition() { return this.pos; } @Override public void close() { } }; } }); autocompleteContact.setAdapter(contactsCursorAdapter); autocompleteContact.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int index, long id) { Cursor cursor = (Cursor) adapter.getItemAtPosition(index); autocompleteContact.setText(cursor.getString(1)); } }); // autocompleteContact.setAdapter(new ArrayAdapter<String> // (this, R.layout.autocomplete, new String[] {"alfa", "beta", "gamma"})); }
From source file:org.openintents.shopping.ui.ShoppingActivity.java
/** * Fill input field (AutoCompleteTextView) with suggestions: Unique item * names from all lists are collected. The adapter is filled in the * background.//from w w w . j a v a 2 s .c o m */ public void fillAutoCompleteTextViewAdapter(final AutoCompleteTextView textView) { boolean limit_selections = PreferenceActivity.getCompleteFromCurrentListOnlyFromPrefs(this); String listId = null; if (limit_selections) { listId = mListUri.getLastPathSegment(); } // TODO: Optimize: This routine is called too often. if (debug) { Log.d(TAG, "fill AutoCompleteTextViewAdapter"); } new AsyncTask<String, Integer, ArrayAdapter<String>>() { ArrayAdapter<String> adapter; @Override protected ArrayAdapter<String> doInBackground(String... params) { return fillAutoCompleteAdapter(params[0]); } @Override protected void onPostExecute(ArrayAdapter<String> adapter) { if (textView != null) { // use result from doInBackground() textView.setAdapter(adapter); } } private ArrayAdapter<String> fillAutoCompleteAdapter(String listId) { // Create list of item names Uri uri; String retCol; if (listId == null) { uri = Items.CONTENT_URI; retCol = Items.NAME; } else { uri = Uri.parse("content://org.openintents.shopping/containsfull/list").buildUpon() .appendPath(listId).build(); retCol = "items.name"; } List<String> autocompleteItems = new LinkedList<String>(); Cursor c = getContentResolver().query(uri, new String[] { retCol }, null, null, retCol + " asc"); if (c != null) { String lastitem = ""; while (c.moveToNext()) { String newitem = c.getString(0); // Only add items if they have not been added previously // (list is sorted) if (!newitem.equals(lastitem)) { autocompleteItems.add(newitem); lastitem = newitem; } } c.close(); } return new ArrayAdapter<String>(ShoppingActivity.this, android.R.layout.simple_dropdown_item_1line, autocompleteItems); } }.execute(listId); }
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;/* ww w. j ava 2s . 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(); }
From source file:pro.dbro.bart.TheActivity.java
/** Called when the activity is first created. */ @Override/*from w ww.j a v a 2 s . c om*/ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //TESTING: enable crittercism Crittercism.init(getApplicationContext(), SECRETS.CRITTERCISM_SECRET); if (Build.VERSION.SDK_INT < 11) { //If API 14+, The ActionBar will be hidden with this call this.requestWindowFeature(Window.FEATURE_NO_TITLE); } setContentView(R.layout.main); tableLayout = (TableLayout) findViewById(R.id.tableLayout); tableContainerLayout = (LinearLayout) findViewById(R.id.tableContainerLayout); c = this; res = getResources(); prefs = getSharedPreferences("PREFS", 0); editor = prefs.edit(); if (prefs.getBoolean("first_timer", true)) { TextView greetingTv = (TextView) View.inflate(c, R.layout.tabletext, null); greetingTv.setText(Html.fromHtml(getString(R.string.greeting))); greetingTv.setTextSize(18); greetingTv.setPadding(0, 0, 0, 0); greetingTv.setMovementMethod(LinkMovementMethod.getInstance()); new AlertDialog.Builder(c).setTitle("Welcome to Open BART").setIcon(R.drawable.ic_launcher) .setView(greetingTv).setPositiveButton("Okay!", null).show(); editor.putBoolean("first_timer", false); editor.commit(); } // LocalBroadCast Stuff LocalBroadcastManager.getInstance(this).registerReceiver(serviceStateMessageReceiver, new IntentFilter("service_status_change")); // infoLayout is at the bottom of the screen // currently contains the stop service label infoLayout = (LinearLayout) findViewById(R.id.infoLayout); // Assign the stationSuggestions Set stationSuggestions = new ArrayList(); // Assign the bart station list to the autocompletetextviews ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, BART.STATIONS); originTextView = (AutoCompleteTextView) findViewById(R.id.originTv); // Set tag for array adapter switch originTextView.setTag(R.id.TextInputShowingSuggestions, "false"); fareTv = (TextView) findViewById(R.id.fareTv); stopServiceTv = (TextView) findViewById(R.id.stopServiceTv); destinationTextView = (AutoCompleteTextView) findViewById(R.id.destinationTv); destinationTextView.setTag(R.id.TextInputShowingSuggestions, "false"); destinationTextView.setAdapter(adapter); originTextView.setAdapter(adapter); // Retrieve TextView inputs from saved preferences if (prefs.contains("origin") && prefs.contains("destination")) { //state= originTextView,destinationTextView String origin = prefs.getString("origin", ""); String destination = prefs.getString("destination", ""); if (origin.compareTo("") != 0) originTextView.setThreshold(200); // disable auto-complete until new text entered if (destination.compareTo("") != 0) destinationTextView.setThreshold(200); // disable auto-complete until new text entered originTextView.setText(origin); destinationTextView.setText(destination); validateInputAndDoRequest(); } // Retrieve station suggestions from file storage try { ArrayList<StationSuggestion> storedSuggestions = (ArrayList<StationSuggestion>) LocalPersistence .readObjectFromFile(c, res.getResourceEntryName(R.string.StationSuggestionFileName)); // If stored StationSuggestions are found, apply them if (storedSuggestions != null) { stationSuggestions = storedSuggestions; Log.d("stationSuggestions", "Loaded"); } else Log.d("stationSuggestions", "Not Found"); } catch (Throwable t) { // don't sweat it } ImageButton map = (ImageButton) findViewById(R.id.map); map.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent = new Intent(c, MapActivity.class); startActivity(intent); } }); ImageButton reverse = (ImageButton) findViewById(R.id.reverse); reverse.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Editable originTempText = originTextView.getText(); originTextView.setText(destinationTextView.getText()); destinationTextView.setText(originTempText); validateInputAndDoRequest(); } }); // Handles restoring TextView input when focus lost, if no new input entered // previous input is stored in the target View Tag attribute // Assumes the target view is a TextView // TODO:This works but starts autocomplete when the view loses focus after clicking outside the autocomplete listview OnFocusChangeListener inputOnFocusChangeListener = new OnFocusChangeListener() { @Override public void onFocusChange(View inputTextView, boolean hasFocus) { if (inputTextView.getTag(R.id.TextInputMemory) != null && !hasFocus && ((TextView) inputTextView).getText().toString().compareTo("") == 0) { //Log.v("InputTextViewTagGet","orig: "+ inputTextView.getTag()); ((TextView) inputTextView).setText(inputTextView.getTag(R.id.TextInputMemory).toString()); } } }; originTextView.setOnFocusChangeListener(inputOnFocusChangeListener); destinationTextView.setOnFocusChangeListener(inputOnFocusChangeListener); // When the TextView is clicked, store current text in TextView's Tag property, clear displayed text // and enable Auto-Completing after first character entered OnTouchListener inputOnTouchListener = new OnTouchListener() { @Override public boolean onTouch(View inputTextView, MotionEvent me) { // Only perform this logic on finger-down if (me.getAction() == me.ACTION_DOWN) { inputTextView.setTag(R.id.TextInputMemory, ((TextView) inputTextView).getText().toString()); Log.d("adapterSwitch", "suggestions"); ((AutoCompleteTextView) inputTextView).setThreshold(1); ((TextView) inputTextView).setText(""); // TESTING // set tag to be retrieved on input entered to set adapter back to station list // The key of a tag must be a unique ID resource inputTextView.setTag(R.id.TextInputShowingSuggestions, "true"); ArrayList<StationSuggestion> prunedSuggestions = new ArrayList<StationSuggestion>(); // copy suggestions for (int x = 0; x < stationSuggestions.size(); x++) { prunedSuggestions.add(stationSuggestions.get(x)); } // Check for and remove other text input's value from stationSuggestions if (inputTextView.equals(findViewById(R.id.originTv))) { // If the originTv is clicked, remove the destinationTv's value from prunedSuggestions if (prunedSuggestions.contains(new StationSuggestion( ((TextView) findViewById(R.id.destinationTv)).getText().toString(), "recent"))) { prunedSuggestions.remove(new StationSuggestion( ((TextView) findViewById(R.id.destinationTv)).getText().toString(), "recent")); } } else if (inputTextView.equals(findViewById(R.id.destinationTv))) { // If the originTv is clicked, remove the destinationTv's value from prunedSuggestions if (prunedSuggestions.contains(new StationSuggestion( ((TextView) findViewById(R.id.originTv)).getText().toString(), "recent"))) { prunedSuggestions.remove(new StationSuggestion( ((TextView) findViewById(R.id.originTv)).getText().toString(), "recent")); } } //if(stationSuggestions.contains(new StationSuggestion(((TextView)inputTextView).getText().toString(),"recent"))) // if available, add localStation to prunedSuggestions if (localStation.compareTo("") != 0) { if (BART.REVERSE_STATION_MAP.get(localStation) != null) { // If a valid localStation (based on DeviceLocation) is available: // remove localStations from recent suggestions (if it exists there) // and add as nearby station prunedSuggestions.remove( new StationSuggestion(BART.REVERSE_STATION_MAP.get(localStation), "recent")); prunedSuggestions.add( new StationSuggestion(BART.REVERSE_STATION_MAP.get(localStation), "nearby")); } } // TESTING: Set Custom ArrayAdapter to hold recent/nearby stations TextPlusIconArrayAdapter adapter = new TextPlusIconArrayAdapter(c, prunedSuggestions); ((AutoCompleteTextView) inputTextView).setAdapter(adapter); // force drop-down to appear, overriding requirement that at least one char is entered ((AutoCompleteTextView) inputTextView).showDropDown(); // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, // android.R.layout.simple_dropdown_item_1line, BART.STATIONS); } // Allow Android to handle additional actions - i.e: TextView takes focus return false; } }; originTextView.setOnTouchListener(inputOnTouchListener); destinationTextView.setOnTouchListener(inputOnTouchListener); // Autocomplete ListView item select listener originTextView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) { Log.d("OriginTextView", "item clicked"); AutoCompleteTextView originTextView = (AutoCompleteTextView) findViewById(R.id.originTv); originTextView.setThreshold(200); //hideSoftKeyboard(arg1); // calling hideSoftKeyboard with arg1 doesn't work with stationSuggestion adapter hideSoftKeyboard(findViewById(R.id.inputLinearLayout)); // Add selected station to stationSuggestions ArrayList if it doesn't exist if (!stationSuggestions .contains((new StationSuggestion(originTextView.getText().toString(), "recent")))) { stationSuggestions.add(0, new StationSuggestion(originTextView.getText().toString(), "recent")); // if the stationSuggestion arraylist is over the max size, remove the last item if (stationSuggestions.size() > STATION_SUGGESTION_SIZE) { stationSuggestions.remove(stationSuggestions.size() - 1); } } // Else, increment click count for that recent else { stationSuggestions .get(stationSuggestions.indexOf( (new StationSuggestion(originTextView.getText().toString(), "recent")))) .addHit(); } validateInputAndDoRequest(); } }); destinationTextView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) { Log.d("DestinationTextView", "item clicked"); // Actv not available as arg1 AutoCompleteTextView destinationTextView = (AutoCompleteTextView) findViewById(R.id.destinationTv); destinationTextView.setThreshold(200); //hideSoftKeyboard(arg1); hideSoftKeyboard(findViewById(R.id.inputLinearLayout)); // Add selected station to stationSuggestions set if (!stationSuggestions .contains((new StationSuggestion(destinationTextView.getText().toString(), "recent")))) { Log.d("DestinationTextView", "adding station"); stationSuggestions.add(0, new StationSuggestion(destinationTextView.getText().toString(), "recent")); if (stationSuggestions.size() > STATION_SUGGESTION_SIZE) { stationSuggestions.remove(stationSuggestions.size() - 1); } } // If station exists in StationSuggestions, increment hit else { stationSuggestions .get(stationSuggestions.indexOf( (new StationSuggestion(destinationTextView.getText().toString(), "recent")))) .addHit(); //Log.d("DestinationTextView",String.valueOf(stationSuggestions.get(stationSuggestions.indexOf((new StationSuggestion(destinationTextView.getText().toString(),"recent")))).hits)); } //If a valid origin station is not entered, return if (BART.STATION_MAP.get(originTextView.getText().toString()) == null) return; validateInputAndDoRequest(); //lastRequest = "etd"; //String url = "http://api.bart.gov/api/etd.aspx?cmd=etd&orig="+originStation+"&key=MW9S-E7SL-26DU-VV8V"; // TEMP: For testing route function //lastRequest = "route"; //bartApiRequest(); } }); //OnKeyListener only gets physical device keyboard events (except the softkeyboard delete key. hmmm) originTextView.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { //Log.d("seachScreen", "afterTextChanged"); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { //Log.d("seachScreen", "beforeTextChanged"); } public void onTextChanged(CharSequence s, int start, int before, int count) { ArrayAdapter<String> adapter = new ArrayAdapter<String>(c, android.R.layout.simple_dropdown_item_1line, BART.STATIONS); if (((String) ((TextView) findViewById(R.id.originTv)).getTag(R.id.TextInputShowingSuggestions)) .compareTo("true") == 0) { ((TextView) findViewById(R.id.originTv)).setTag(R.id.TextInputShowingSuggestions, "false"); ((AutoCompleteTextView) findViewById(R.id.originTv)).setAdapter(adapter); } Log.d("seachScreen", s.toString()); } }); destinationTextView.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { //Log.d("seachScreen", "afterTextChanged"); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { //Log.d("seachScreen", "beforeTextChanged"); } public void onTextChanged(CharSequence s, int start, int before, int count) { ArrayAdapter<String> adapter = new ArrayAdapter<String>(c, android.R.layout.simple_dropdown_item_1line, BART.STATIONS); if (((String) ((TextView) findViewById(R.id.destinationTv)) .getTag(R.id.TextInputShowingSuggestions)).compareTo("true") == 0) { ((TextView) findViewById(R.id.destinationTv)).setTag(R.id.TextInputShowingSuggestions, "false"); ((AutoCompleteTextView) findViewById(R.id.destinationTv)).setAdapter(adapter); } Log.d("seachScreen", s.toString()); } }); }
From source file:it.sasabz.android.sasabus.fragments.OnlineSearchFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.inflater_glob = inflater; result = inflater.inflate(R.layout.online_search_layout, container, false); Date datum = new Date(); SimpleDateFormat simple = new SimpleDateFormat("dd.MM.yyyy HH:mm"); TextView datetime = (TextView) result.findViewById(R.id.time); String datetimestring = ""; datetimestring = simple.format(datum); datetime.setText(datetimestring);//w w w . j a v a2 s. c o m Button search = (Button) result.findViewById(R.id.search); search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AutoCompleteTextView from = (AutoCompleteTextView) result.findViewById(R.id.from_text); AutoCompleteTextView to = (AutoCompleteTextView) result.findViewById(R.id.to_text); TextView datetime = (TextView) result.findViewById(R.id.time); String from_txt = getThis().getResources().getString(R.string.from_txt); if ((!from.getText().toString().trim().equals("") || !from.getHint().toString().trim().equals(from_txt)) && !to.getText().toString().trim().equals("")) { //Intent getSelect = new Intent(getThis().getActivity(), OnlineSelectStopActivity.class); String fromtext = ""; if (from.getText().toString().trim().equals("")) fromtext = from.getHint().toString(); else fromtext = from.getText().toString(); String totext = to.getText().toString(); fromtext = "(" + fromtext.replace(" -", ")"); totext = "(" + totext.replace(" -", ")"); Fragment fragment = new OnlineSelectFragment(fromtext, totext, datetime.getText().toString()); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction ft = fragmentManager.beginTransaction(); Fragment old = fragmentManager.findFragmentById(R.id.onlinefragment); if (old != null) { ft.remove(old); } ft.add(R.id.onlinefragment, fragment); ft.addToBackStack(null); ft.commit(); fragmentManager.executePendingTransactions(); } } }); datetime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Create the dialog final Dialog mDateTimeDialog = new Dialog(getThis().getActivity()); // Inflate the root layout final RelativeLayout mDateTimeDialogView = (RelativeLayout) inflater_glob .inflate(R.layout.date_time_dialog, null); // Grab widget instance final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView .findViewById(R.id.DateTimePicker); TextView dt = (TextView) result.findViewById(R.id.time); String datetimestring = dt.getText().toString(); SimpleDateFormat datetimeformat = new SimpleDateFormat("dd.MM.yyyy HH:mm"); Date datetime = null; try { datetime = datetimeformat.parse(datetimestring); } catch (Exception e) { ; } mDateTimePicker.updateTime(datetime.getHours(), datetime.getMinutes()); mDateTimePicker.updateDate(datetime.getYear() + 1900, datetime.getMonth(), datetime.getDate()); // Check is system is set to use 24h time (this doesn't seem to // work as expected though) final String timeS = android.provider.Settings.System.getString( getThis().getActivity().getContentResolver(), android.provider.Settings.System.TIME_12_24); final boolean is24h = !(timeS == null || timeS.equals("12")); ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)) .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mDateTimePicker.clearFocus(); String datetimestring = ""; int day = mDateTimePicker.get(Calendar.DAY_OF_MONTH); int month = mDateTimePicker.get(Calendar.MONTH) + 1; int year = mDateTimePicker.get(Calendar.YEAR); int hour = 0; int min = 0; int append = 0; if (mDateTimePicker.is24HourView()) { hour = mDateTimePicker.get(Calendar.HOUR_OF_DAY); min = mDateTimePicker.get(Calendar.MINUTE); } else { hour = mDateTimePicker.get(Calendar.HOUR); min = mDateTimePicker.get(Calendar.MINUTE); if (mDateTimePicker.get(Calendar.AM_PM) == Calendar.AM) { append = 1; } else { append = 2; } } if (day < 10) { datetimestring += "0"; } datetimestring += (day + "."); if (month < 10) { datetimestring += "0"; } datetimestring += (month + "." + year + " "); if (hour < 10) { datetimestring += "0"; } datetimestring += (hour + ":"); if (min < 10) { datetimestring += "0"; } datetimestring += min; switch (append) { case 1: datetimestring += " AM"; break; case 2: datetimestring += " PM"; break; } TextView time = (TextView) result.findViewById(R.id.time); time.setText(datetimestring); mDateTimeDialog.dismiss(); } }); // Cancel the dialog when the "Cancel" button is clicked ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)) .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub mDateTimeDialog.cancel(); } }); // Reset Date and Time pickers when the "Reset" button is // clicked ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime)) .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub mDateTimePicker.reset(); } }); // Setup TimePicker mDateTimePicker.setIs24HourView(is24h); // No title on the dialog window mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // Set the dialog content view mDateTimeDialog.setContentView(mDateTimeDialogView); // Display the dialog mDateTimeDialog.show(); } }); ImageButton datepicker = (ImageButton) result.findViewById(R.id.datepicker); datepicker.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Create the dialog final Dialog mDateTimeDialog = new Dialog(getThis().getActivity()); // Inflate the root layout final RelativeLayout mDateTimeDialogView = (RelativeLayout) inflater_glob .inflate(R.layout.date_time_dialog, null); // Grab widget instance final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView .findViewById(R.id.DateTimePicker); TextView dt = (TextView) result.findViewById(R.id.time); String datetimestring = dt.getText().toString(); SimpleDateFormat datetimeformat = new SimpleDateFormat("dd.MM.yyyy HH:mm"); Date datetime = null; try { datetime = datetimeformat.parse(datetimestring); } catch (Exception e) { ; } mDateTimePicker.updateTime(datetime.getHours(), datetime.getMinutes()); mDateTimePicker.updateDate(datetime.getYear() + 1900, datetime.getMonth(), datetime.getDate()); // Check is system is set to use 24h time (this doesn't seem to // work as expected though) final String timeS = android.provider.Settings.System.getString( getThis().getActivity().getContentResolver(), android.provider.Settings.System.TIME_12_24); final boolean is24h = !(timeS == null || timeS.equals("12")); // Update demo TextViews when the "OK" button is clicked ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)) .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mDateTimePicker.clearFocus(); String datetimestring = ""; int day = mDateTimePicker.get(Calendar.DAY_OF_MONTH); int month = mDateTimePicker.get(Calendar.MONTH) + 1; int year = mDateTimePicker.get(Calendar.YEAR); int hour = 0; int min = 0; int append = 0; if (mDateTimePicker.is24HourView()) { hour = mDateTimePicker.get(Calendar.HOUR_OF_DAY); min = mDateTimePicker.get(Calendar.MINUTE); } else { hour = mDateTimePicker.get(Calendar.HOUR); min = mDateTimePicker.get(Calendar.MINUTE); if (mDateTimePicker.get(Calendar.AM_PM) == Calendar.AM) { append = 1; } else { append = 2; } } if (day < 10) { datetimestring += "0"; } datetimestring += (day + "."); if (month < 10) { datetimestring += "0"; } datetimestring += (month + "." + year + " "); if (hour < 10) { datetimestring += "0"; } datetimestring += (hour + ":"); if (min < 10) { datetimestring += "0"; } datetimestring += min; switch (append) { case 1: datetimestring += " AM"; break; case 2: datetimestring += " PM"; break; } TextView time = (TextView) result.findViewById(R.id.time); time.setText(datetimestring); mDateTimeDialog.dismiss(); } }); // Cancel the dialog when the "Cancel" button is clicked ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)) .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub mDateTimeDialog.cancel(); } }); // Reset Date and Time pickers when the "Reset" button is // clicked ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime)) .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub mDateTimePicker.reset(); } }); // Setup TimePicker mDateTimePicker.setIs24HourView(is24h); // No title on the dialog window mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // Set the dialog content view mDateTimeDialog.setContentView(mDateTimeDialogView); // Display the dialog mDateTimeDialog.show(); } }); from = (AutoCompleteTextView) result.findViewById(R.id.from_text); to = (AutoCompleteTextView) result.findViewById(R.id.to_text); from.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { InputMethodManager mgr = (InputMethodManager) getActivity() .getSystemService(Context.INPUT_METHOD_SERVICE); mgr.hideSoftInputFromWindow(from.getWindowToken(), 0); } }); to.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { InputMethodManager mgr = (InputMethodManager) getActivity() .getSystemService(Context.INPUT_METHOD_SERVICE); mgr.hideSoftInputFromWindow(to.getWindowToken(), 0); } }); LocationManager locman = (LocationManager) this.getActivity().getSystemService(Context.LOCATION_SERVICE); Location lastloc = locman.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (MySQLiteDBAdapter.exists(this.getActivity())) { if (lastloc == null) { lastloc = locman.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } if (lastloc != null) { try { Palina palina = PalinaList.getPalinaGPS(lastloc); if (palina != null) { from.setHint(palina.toString()); } } catch (Exception e) { Log.e("HomeActivity", "Fehler bei der Location", e); } } else { Log.v("HomeActivity", "No location found!!"); } Vector<DBObject> palinalist = PalinaList.getNameList(); MyAutocompleteAdapter adapterfrom = new MyAutocompleteAdapter(this.getActivity(), android.R.layout.simple_list_item_1, palinalist); MyAutocompleteAdapter adapterto = new MyAutocompleteAdapter(this.getActivity(), android.R.layout.simple_list_item_1, palinalist); from.setAdapter(adapterfrom); to.setAdapter(adapterto); InputMethodManager mgr = (InputMethodManager) getActivity() .getSystemService(Context.INPUT_METHOD_SERVICE); mgr.hideSoftInputFromWindow(from.getWindowToken(), 0); mgr.hideSoftInputFromWindow(to.getWindowToken(), 0); } Button favorites = (Button) result.findViewById(R.id.favorites); favorites.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SelectFavoritenDialog dialog = new SelectFavoritenDialog(getThis()); dialog.show(); } }); Button mappicker = (Button) result.findViewById(R.id.map); mappicker.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), MapSelectActivity.class); startActivityForResult(intent, REQUESTCODE_ACTIVITY); } }); return result; }