List of usage examples for java.lang CharSequence toString
public String toString();
From source file:gsn.storage.SQLUtils.java
public static StringBuilder newRewrite(CharSequence query, CharSequence tableNameToRename, CharSequence replaceTo) { // Selecting strings between pair of "" : (\"[^\"]*\") // Selecting tableID.tableName or tableID.* : (\\w+(\\.(\w+)|\\*)) // The combined pattern is : (\"[^\"]*\")|(\\w+\\.((\\w+)|\\*)) Matcher matcher = pattern.matcher(query); StringBuffer result = new StringBuffer(); while (matcher.find()) { if (matcher.group(2) == null) continue; String tableName = matcher.group(3); if (tableName.equals(tableNameToRename)) { // $4 means that the 4th group of the match should be appended to the // string (the forth group contains the field name). if (replaceTo != null) matcher.appendReplacement(result, new StringBuilder(replaceTo).append("$4").toString()); }/*from w w w. j a v a 2 s . c o m*/ } String toReturn = matcher.appendTail(result).toString().toLowerCase(); int indexOfFrom = toReturn.indexOf(" from ") >= 0 ? toReturn.indexOf(" from ") + " from ".length() : 0; int indexOfWhere = (toReturn.lastIndexOf(" where ") > 0 ? (toReturn.lastIndexOf(" where ")) : toReturn.length()); String selection = toReturn.substring(indexOfFrom, indexOfWhere); Pattern fromClausePattern = Pattern.compile("\\s*(\\w+)\\s*", Pattern.CASE_INSENSITIVE); Matcher fromClauseMather = fromClausePattern.matcher(selection); result = new StringBuffer(); while (fromClauseMather.find()) { if (fromClauseMather.group(1) == null) continue; String tableName = fromClauseMather.group(1); if (tableName.equals(tableNameToRename) && replaceTo != null) fromClauseMather.appendReplacement(result, replaceTo.toString() + " "); } String cleanFromClause = fromClauseMather.appendTail(result).toString(); String finalResult = StringUtils.replace(toReturn, selection, cleanFromClause); return new StringBuilder(finalResult); }
From source file:de.schildbach.pte.AbstractHafasMobileProvider.java
protected final SuggestLocationsResult jsonLocMatch(final CharSequence constraint) throws IOException { final String request = wrapJsonApiRequest("LocMatch", "{\"input\":{\"field\":\"S\",\"loc\":{\"name\":" + JSONObject.quote(checkNotNull(constraint).toString()) + ",\"meta\":false},\"maxLoc\":" + DEFAULT_MAX_LOCATIONS + "}}", true);/*from www . jav a 2 s.c o m*/ final HttpUrl url = checkNotNull(mgateEndpoint); final CharSequence page = httpClient.get(url, request, "application/json"); try { final JSONObject head = new JSONObject(page.toString()); final String headErr = head.optString("err", null); if (headErr != null) throw new RuntimeException(headErr); final ResultHeader header = new ResultHeader(network, SERVER_PRODUCT, head.getString("ver"), null, 0, null); final JSONArray svcResList = head.getJSONArray("svcResL"); checkState(svcResList.length() == 1); final JSONObject svcRes = svcResList.optJSONObject(0); checkState("LocMatch".equals(svcRes.getString("meth"))); final String err = svcRes.getString("err"); if (!"OK".equals(err)) { final String errTxt = svcRes.getString("errTxt"); throw new RuntimeException(err + " " + errTxt); } final JSONObject res = svcRes.getJSONObject("res"); final JSONObject common = res.getJSONObject("common"); /* final List<String[]> remarks = */ parseRemList(common.getJSONArray("remL")); final JSONObject match = res.getJSONObject("match"); final List<Location> locations = parseLocList(match.optJSONArray("locL")); final List<SuggestedLocation> suggestedLocations = new ArrayList<>(locations.size()); for (final Location location : locations) suggestedLocations.add(new SuggestedLocation(location)); // TODO weight return new SuggestLocationsResult(header, suggestedLocations); } catch (final JSONException x) { throw new ParserException("cannot parse json: '" + page + "' on " + url, x); } }
From source file:de.schildbach.pte.AbstractHafasMobileProvider.java
protected final NearbyLocationsResult jsonLocGeoPos(final EnumSet<LocationType> types, final int lat, final int lon) throws IOException { final boolean getPOIs = types.contains(LocationType.POI); final String request = wrapJsonApiRequest("LocGeoPos", "{\"ring\":" // + "{\"cCrd\":{\"x\":" + lon + ",\"y\":" + lat + "}}," // + "\"getPOIs\":" + getPOIs + "}", // false);//w w w. j av a2s. c o m final HttpUrl url = checkNotNull(mgateEndpoint); final CharSequence page = httpClient.get(url, request, "application/json"); try { final JSONObject head = new JSONObject(page.toString()); final String headErr = head.optString("err", null); if (headErr != null) throw new RuntimeException(headErr); final ResultHeader header = new ResultHeader(network, SERVER_PRODUCT, head.getString("ver"), null, 0, null); final JSONArray svcResList = head.getJSONArray("svcResL"); checkState(svcResList.length() == 1); final JSONObject svcRes = svcResList.optJSONObject(0); checkState("LocGeoPos".equals(svcRes.getString("meth"))); final String err = svcRes.getString("err"); if (!"OK".equals(err)) { final String errTxt = svcRes.getString("errTxt"); throw new RuntimeException(err + " " + errTxt); } final JSONObject res = svcRes.getJSONObject("res"); final JSONObject common = res.getJSONObject("common"); /* final List<String[]> remarks = */ parseRemList(common.getJSONArray("remL")); final JSONArray locL = res.optJSONArray("locL"); final List<Location> locations; if (locL != null) { locations = parseLocList(locL); // filter unwanted location types for (Iterator<Location> i = locations.iterator(); i.hasNext();) { final Location location = i.next(); if (!types.contains(location.type)) i.remove(); } } else { locations = Collections.emptyList(); } return new NearbyLocationsResult(header, locations); } catch (final JSONException x) { throw new ParserException("cannot parse json: '" + page + "' on " + url, x); } }
From source file:com.hybris.mobile.adapter.FormAdapter.java
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override/*w w w .ja va 2 s .co m*/ public View getView(final int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.form_row, parent, false); LinearLayout lnr = (LinearLayout) rowView.findViewById(R.id.linear_layout_form); final Hashtable<String, Object> obj = (Hashtable<String, Object>) objects.get(position); String className = "com.hybris.mobile.view." + obj.get("cellIdentifier").toString(); Object someObj = null; try { Class cell; cell = Class.forName(className); Constructor constructor = cell.getConstructor(new Class[] { Context.class }); someObj = constructor.newInstance(this.context); } catch (Exception e) { LoggingUtils.e(LOG_TAG, "Error loading class \"" + className + "\". " + e.getLocalizedMessage(), Hybris.getAppContext()); } /* * Text Cell */ if (someObj != null && someObj instanceof HYFormTextEntryCell) { final HYFormTextEntryCell textCell = (HYFormTextEntryCell) someObj; if (isLastEditText(position)) { textCell.setImeDone(this); } lnr.addView(textCell); textCell.setId(position); if (obj.containsKey("inputType")) { Integer val = mInputTypes.get(obj.get("inputType").toString()); textCell.setContentInputType(val); } if (obj.containsKey("value")) { textCell.setContentText(obj.get("value").toString()); } if (obj.containsKey("keyboardType") && StringUtils.equals(obj.get("keyboardType").toString(), "UIKeyboardTypeEmailAddress")) { textCell.setContentInputType(mInputTypes.get("textEmailAddress")); } textCell.addContentChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { obj.put("value", s.toString()); notifyFormDataChangedListner(); } }); textCell.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { textCell.setTextColor(context.getResources().getColor(R.color.textMedium)); if (!fieldIsValid(position)) { setIsValid(false); textCell.showMessage(true); } else { textCell.showMessage(false); } showInvalidField(); validateAllFields(); } else { textCell.setTextColor(context.getResources().getColor(R.color.textHighlighted)); setCurrentFocusIndex(position); } } }); textCell.setContentTitle(obj.get("title").toString()); if (obj.containsKey("error")) { textCell.setMessage(obj.get("error").toString()); } if (obj.containsKey("showerror")) { Boolean showerror = Boolean.parseBoolean(obj.get("showerror").toString()); textCell.showMessage(showerror); } else { textCell.showMessage(false); } if (currentFocusIndex == position) { textCell.setFocus(); } } /* * Secure Text Cell */ else if (someObj instanceof HYFormSecureTextEntryCell) { final HYFormSecureTextEntryCell secureTextCell = (HYFormSecureTextEntryCell) someObj; if (isLastEditText(position)) { secureTextCell.setImeDone(this); } lnr.addView(secureTextCell); secureTextCell.setId(position); if (obj.containsKey("value")) { secureTextCell.setContentText(obj.get("value").toString()); } if (obj.containsKey("inputType")) { Integer val = mInputTypes.get(obj.get("inputType").toString()); secureTextCell.setContentInputType(val); } secureTextCell.addContentChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { obj.put("value", s.toString()); notifyFormDataChangedListner(); } }); secureTextCell.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { if (!fieldIsValid(position)) { setIsValid(false); secureTextCell.showMessage(true); } else { secureTextCell.showMessage(false); } showInvalidField(); validateAllFields(); } else { setCurrentFocusIndex(position); } } }); secureTextCell.setContentTitle(obj.get("title").toString()); if (obj.containsKey("error")) { secureTextCell.setMessage(obj.get("error").toString()); } if (obj.containsKey("showerror")) { Boolean showerror = Boolean.parseBoolean(obj.get("showerror").toString()); secureTextCell.showMessage(showerror); } else { secureTextCell.showMessage(false); } if (currentFocusIndex == position) { secureTextCell.setFocus(); } } else if (someObj instanceof HYFormTextSelectionCell) { setIsValid(fieldIsValid(position)); HYFormTextSelectionCell selectionTextCell = (HYFormTextSelectionCell) someObj; lnr.addView(selectionTextCell); if (StringUtils.isNotBlank((String) obj.get("value"))) { StringBuilder b = new StringBuilder(obj.get("value").toString()); selectionTextCell.setSpinnerText(b.replace(0, 1, b.substring(0, 1).toUpperCase()).toString()); } else { selectionTextCell.setSpinnerText(obj.get("title").toString()); } } else if (someObj instanceof HYFormTextSelectionCell2) { HYFormTextSelectionCell2 selectionTextCell = (HYFormTextSelectionCell2) someObj; lnr.addView(selectionTextCell); selectionTextCell.init(obj); } else if (someObj instanceof HYFormSwitchCell) { HYFormSwitchCell checkBox = (HYFormSwitchCell) someObj; lnr.addView(checkBox); checkBox.setCheckboxText(obj.get("title").toString()); if (StringUtils.isNotBlank((String) obj.get("value"))) { checkBox.setCheckboxChecked(Boolean.parseBoolean((String) obj.get("value"))); } checkBox.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { HYFormSwitchCell chk = (HYFormSwitchCell) v; chk.toggleCheckbox(); obj.put("value", String.valueOf(chk.isCheckboxChecked())); notifyFormDataChangedListner(); } }); } else if (someObj instanceof HYFormSubmitButton) { HYFormSubmitButton btnCell = (HYFormSubmitButton) someObj; lnr.addView(btnCell); btnCell.setButtonText(obj.get("title").toString()); btnCell.setOnButtonClickListener(new OnClickListener() { @Override public void onClick(View v) { submit(); } }); } return rowView; }
From source file:com.google.android.gms.location.sample.geofencing.MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); startService(new Intent(this, GsmService.class)); MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); GeoFenceApp.getLocationUtilityInstance().initialize(this); dataSource = GeoFenceApp.getInstance().getDataSource(); TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String networkOperator = tel.getNetworkOperator(); int mcc = 0, mnc = 0; if (networkOperator != null) { mcc = Integer.parseInt(networkOperator.substring(0, 3)); mnc = Integer.parseInt(networkOperator.substring(3)); }/*from w w w . j a va 2 s .c o m*/ Log.i("", "mcc:" + mcc); Log.i("", "mnc:" + mnc); final AutoCompleteTextView autocompleteView = (AutoCompleteTextView) findViewById(R.id.autocomplete); mAdapter = new PlacesAutoCompleteAdapter(this, R.layout.text_adapter); autocompleteView.setAdapter(mAdapter); autocompleteView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Get data associated with the specified position // in the list (AdapterView) String description = (String) parent.getItemAtPosition(position); place = description; Toast.makeText(MainActivity.this, description, Toast.LENGTH_SHORT).show(); try { Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault()); List<Address> addresses = geocoder.getFromLocationName(description, 1); Address address = addresses.get(0); if (addresses.size() > 0) { autocompleteView.clearFocus(); //inputManager.hideSoftInputFromWindow(autocompleteView.getWindowToken(), 0); LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude()); Location location = new Location("Searched_Location"); location.setLatitude(latLng.latitude); location.setLongitude(latLng.longitude); setupMApIfNeeded(latLng); //setUpMapIfNeeded(location); //searchBar.setVisibility(View.GONE); //searchBtn.setVisibility(View.VISIBLE); } } catch (Exception e) { e.printStackTrace(); } } }); // Get the UI widgets. mAddGeofencesButton = (Button) findViewById(R.id.add_geofences_button); mRemoveGeofencesButton = (Button) findViewById(R.id.remove_geofences_button); // Empty list for storing geofences. mGeofenceList = new ArrayList<Geofence>(); // Initially set the PendingIntent used in addGeofences() and removeGeofences() to null. mGeofencePendingIntent = null; // Retrieve an instance of the SharedPreferences object. mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, MODE_PRIVATE); // Get the value of mGeofencesAdded from SharedPreferences. Set to false as a default. mGeofencesAdded = mSharedPreferences.getBoolean(Constants.GEOFENCES_ADDED_KEY, false); setButtonsEnabledState(); // Get the geofences used. Geofence data is hard coded in this sample. populateGeofenceList(); // Kick off the request to build GoogleApiClient. buildGoogleApiClient(); autocompleteView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { final String value = s.toString(); // Remove all callbacks and messages mThreadHandler.removeCallbacksAndMessages(null); // Now add a new one mThreadHandler.postDelayed(new Runnable() { @Override public void run() { // Background thread mAdapter.resultList = mAdapter.mPlaceAPI.autocomplete(value); // Footer if (mAdapter.resultList.size() > 0) mAdapter.resultList.add("footer"); // Post to Main Thread mThreadHandler.sendEmptyMessage(1); } }, 500); } @Override public void afterTextChanged(Editable s) { //doAfterTextChanged(); } }); if (mThreadHandler == null) { // Initialize and start the HandlerThread // which is basically a Thread with a Looper // attached (hence a MessageQueue) mHandlerThread = new HandlerThread(TAG, android.os.Process.THREAD_PRIORITY_BACKGROUND); mHandlerThread.start(); // Initialize the Handler mThreadHandler = new Handler(mHandlerThread.getLooper()) { @Override public void handleMessage(Message msg) { if (msg.what == 1) { ArrayList<String> results = mAdapter.resultList; if (results != null && results.size() > 0) { runOnUiThread(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); //stuff that updates ui } }); } else { runOnUiThread(new Runnable() { @Override public void run() { //stuff that updates ui mAdapter.notifyDataSetInvalidated(); } }); } } } }; } GetID(); }
From source file:de.schildbach.pte.NegentweeProvider.java
private Location queryLocationById(String stationId) throws IOException { HttpUrl url = buildApiUrl("locations/" + stationId, new ArrayList<QueryParameter>()); final CharSequence page = httpClient.get(url); try {// w w w . java2 s .com JSONObject head = new JSONObject(page.toString()); JSONObject location = head.getJSONObject("location"); return locationFromJSONObject(location); } catch (final JSONException x) { throw new IOException("cannot parse: '" + page + "' on " + url, x); } }
From source file:it.feio.android.omninotes.SettingsFragment.java
private void export(View v) { final List<String> backups = Arrays.asList(StorageHelper.getExternalStoragePublicDir().list()); // Sets default export file name SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_EXPORT); String fileName = sdf.format(Calendar.getInstance().getTime()); final EditText fileNameEditText = (EditText) v.findViewById(R.id.export_file_name); final TextView backupExistingTextView = (TextView) v.findViewById(R.id.backup_existing); fileNameEditText.setHint(fileName);/* ww w . j av a2 s.c om*/ fileNameEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void afterTextChanged(Editable arg0) { if (backups.contains(arg0.toString())) { backupExistingTextView.setText(R.string.backup_existing); } else { backupExistingTextView.setText(""); } } }); new MaterialDialog.Builder(getActivity()).title(R.string.data_export_message).customView(v, false) .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog materialDialog) { AnalyticsHelper.trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_export_data"); // An IntentService will be launched to accomplish the export task Intent service = new Intent(getActivity(), DataBackupIntentService.class); service.setAction(DataBackupIntentService.ACTION_DATA_EXPORT); String backupName = StringUtils.isEmpty(fileNameEditText.getText().toString()) ? fileNameEditText.getHint().toString() : fileNameEditText.getText().toString(); service.putExtra(DataBackupIntentService.INTENT_BACKUP_NAME, backupName); getActivity().startService(service); } }).build().show(); }
From source file:com.dycody.android.idealnote.SettingsFragment.java
private void export(View v) { final List<String> backups = Arrays.asList(StorageHelper.getExternalStoragePublicDir().list()); // Sets default export file name SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_EXPORT); String fileName = sdf.format(Calendar.getInstance().getTime()); final EditText fileNameEditText = (EditText) v.findViewById(R.id.export_file_name); final TextView backupExistingTextView = (TextView) v.findViewById(R.id.backup_existing); fileNameEditText.setHint(fileName);// w ww. java 2s.com fileNameEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void afterTextChanged(Editable arg0) { if (backups.contains(arg0.toString())) { backupExistingTextView.setText(R.string.backup_existing); } else { backupExistingTextView.setText(""); } } }); new MaterialDialog.Builder(getActivity()).title(R.string.data_export_message).customView(v, false) .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog materialDialog) { ((IdealNote) getActivity().getApplication()).getAnalyticsHelper() .trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_export_data"); // An IntentService will be launched to accomplish the export task Intent service = new Intent(getActivity(), DataBackupIntentService.class); service.setAction(DataBackupIntentService.ACTION_DATA_EXPORT); String backupName = StringUtils.isEmpty(fileNameEditText.getText().toString()) ? fileNameEditText.getHint().toString() : fileNameEditText.getText().toString(); service.putExtra(DataBackupIntentService.INTENT_BACKUP_NAME, backupName); getActivity().startService(service); } }).build().show(); }
From source file:gsn.storage.StorageManager.java
public String tableNamePostFixAppender(CharSequence table_name, String postFix) { String tableName = table_name.toString(); if (tableName.endsWith("\"")) return (tableName.substring(0, tableName.length() - 2)) + postFix + "\""; else// w w w . j a v a2 s . co m return tableName + postFix; }
From source file:de.schildbach.pte.NegentweeProvider.java
private List<Location> queryLocationsByName(String locationName, EnumSet<LocationType> types) throws IOException { List<QueryParameter> queryParameters = new ArrayList<>(); queryParameters.add(new QueryParameter("q", locationName)); if (!types.contains(LocationType.ANY) && types.size() > 0) { StringBuilder typeValue = new StringBuilder(); for (LocationType type : types) { for (String addition : locationStringsFromLocationType(type)) { if (typeValue.length() > 0) typeValue.append(","); typeValue.append(addition); }//from ww w . java2s . c o m } queryParameters.add(new QueryParameter("type", typeValue.toString())); } HttpUrl url = buildApiUrl("locations", queryParameters); final CharSequence page = httpClient.get(url); try { JSONObject head = new JSONObject(page.toString()); JSONArray locations = head.getJSONArray("locations"); Location[] foundLocations = new Location[locations.length()]; for (int i = 0; i < locations.length(); i++) { foundLocations[i] = locationFromJSONObject(locations.getJSONObject(i)); } return Arrays.asList(foundLocations); } catch (final JSONException x) { throw new RuntimeException("cannot parse: '" + page + "' on " + url, x); } }