コード例 #1
0
ファイル: BudgetsImpl.java プロジェクト: Guillermo--/BuckWise
  public Budget editBudgetCategoryAndInitialAmount(String category, String inputAmount) {
    Budget budget = getLatestBudget();
    BudgetsDAO budgetsDao = new BudgetsDAO(context);
    List<String> categories = Arrays.asList(budget.getCategories().split(","));
    List<String> initialAmounts = Arrays.asList(budget.getInitialAmounts().split(","));
    int targetIndex = categories.indexOf(category);

    if (inputAmount != null && !inputAmount.isEmpty()) {
      initialAmounts.set(targetIndex, inputAmount);
    }

    String categoriesStr = TextUtils.join(",", categories);
    String initialAmountsStr = TextUtils.join(",", initialAmounts);

    budget.setInitialAmounts(initialAmountsStr);
    budget.setCategories(categoriesStr);
    budget.setAmountStartedWith(calculateAmountStartedWith(budget));
    budget.setAmountAvailable(calculateAmountAvailable(budget));

    Date currentDateForComparison = Util.stringToDate(Util.getCurrentDateTime());
    Date latestDateForComparison = Util.stringToDate(budget.getDateCreated());

    if (currentDateForComparison.after(latestDateForComparison)) {
      budget.setDateCreated(Util.getCurrentDateTime());
      budgetsDao.createBudgetItem(budget);
    } else {
      budgetsDao.updateBudgetCategoryAndInitialAmount(budget);
    }

    return budget;
  }
コード例 #2
0
  @Override
  public Signature createSignature(String peerId, List<String> watchIds) {
    Signature s = new Signature();

    long timestamp = System.currentTimeMillis() / 1000;
    String nonce = "ForeverAlone";
    List<String> watchIdsCopy = new ArrayList<String>();
    watchIdsCopy.addAll(watchIds);

    s.setTimestamp(timestamp);
    s.setNonce(nonce);
    s.setSignedPeerIds(watchIdsCopy);

    List<String> signatureElements = new ArrayList<String>();
    signatureElements.add(appId);

    signatureElements.add(selfPeerId);

    Collections.sort(watchIdsCopy);
    signatureElements.add(TextUtils.join(":", watchIdsCopy));

    signatureElements.add(String.valueOf(timestamp));

    signatureElements.add(nonce);
    /*
     * 此处请一定不要直接复制黏贴到您的代码中
     *
     * 在真实的产品中间,请尽量使用服务器端数据,完成这一步signature赋值操作,以保证服务器安全性
     */
    String sig = hmacSHA1(TextUtils.join(":", signatureElements), SUPER_POWER_KEY);
    s.setSignature(sig);

    return s;
  }
コード例 #3
0
  @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  private void setAllowedVpnPackages(Builder builder) {
    boolean atLeastOneAllowedApp = false;
    for (String pkg : mProfile.mAllowedAppsVpn) {
      try {
        if (mProfile.mAllowedAppsVpnAreDisallowed) {
          builder.addDisallowedApplication(pkg);
        } else {
          builder.addAllowedApplication(pkg);
          atLeastOneAllowedApp = true;
        }
      } catch (PackageManager.NameNotFoundException e) {
        mProfile.mAllowedAppsVpn.remove(pkg);
        VpnStatus.logInfo(R.string.app_no_longer_exists, pkg);
      }
    }

    if (!mProfile.mAllowedAppsVpnAreDisallowed && !atLeastOneAllowedApp) {
      VpnStatus.logDebug(R.string.no_allowed_app, getPackageName());
      try {
        builder.addAllowedApplication(getPackageName());
      } catch (PackageManager.NameNotFoundException e) {
        VpnStatus.logError("This should not happen: " + e.getLocalizedMessage());
      }
    }

    if (mProfile.mAllowedAppsVpnAreDisallowed) {
      VpnStatus.logDebug(
          R.string.disallowed_vpn_apps_info, TextUtils.join(", ", mProfile.mAllowedAppsVpn));
    } else {
      VpnStatus.logDebug(
          R.string.allowed_vpn_apps_info, TextUtils.join(", ", mProfile.mAllowedAppsVpn));
    }
  }
コード例 #4
0
 /**
  * save a list to local SharedPreferences
  *
  * @param context current context
  * @param preKey key
  * @param dataSource list<?>
  */
 public static void saveListToSharedPreferences(
     Context context, String preKey, ArrayList<?> dataSource) {
   try {
     SharedPreferences.Editor editor =
         PreferenceManager.getDefaultSharedPreferences(context).edit();
     editor.remove(preKey).commit();
     String serialized =
         PreferenceManager.getDefaultSharedPreferences(context).getString(preKey, "");
     Log.e("TAG", serialized + " ------- " + TextUtils.join(",", dataSource));
     editor.putString(preKey, TextUtils.join(",", dataSource)).commit();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #5
0
ファイル: GameDBHelper.java プロジェクト: ldumancas/KeepScore
  public Game findMostRecentGame() {
    synchronized (GameDBHelper.class) {
      Cursor cursor = null;
      try {

        String sql =
            new StringBuilder("select ")
                .append(TextUtils.join(",", JOINED_COLUMNS))
                .append(" from ")
                .append(JOINED_TABLES)
                .append(" order by ")
                .append(COLUMN_DATE_SAVED)
                .append(" desc ")
                .append(" limit 1")
                .toString();

        cursor = db.rawQuery(sql, null);
        List<Game> result = convertToGames(cursor);

        return result.isEmpty() ? null : result.get(0);
      } finally {
        if (cursor != null) {
          cursor.close();
        }
      }
    }
  }
コード例 #6
0
 @Override
 protected void onProgressUpdate(String... progress) {
   if (progress != null && progress.length > 0) {
     String msg = TextUtils.join("\n", progress);
     textViewTest.setText(msg);
   } else textViewTest.setText(_action.toString());
 }
コード例 #7
0
ファイル: BudgetsImpl.java プロジェクト: Guillermo--/BuckWise
  public Budget logBudgetExpense(String category, String amountSpent) {
    Budget budget = getLatestBudget();
    BudgetsDAO budgetsDao = new BudgetsDAO(context);
    List<String> categories = Arrays.asList(budget.getCategories().split(","));
    List<String> amountsSpent = Arrays.asList(budget.getAmountsSpent().split(","));
    int targetIndex = categories.indexOf(category);

    double targetAmountSpent = Double.parseDouble(amountsSpent.get(targetIndex));
    double newAmountSpent = targetAmountSpent + Double.parseDouble(amountSpent);
    amountsSpent.set(targetIndex, String.valueOf(newAmountSpent));
    String amountsSpentStr = TextUtils.join(",", amountsSpent);
    budget.setAmountsSpent(amountsSpentStr);
    budget.setAmountAvailable(calculateAmountAvailable(budget));

    Date currentDateForComparison = Util.stringToDate(Util.getCurrentDateTime());
    Date latestDateForComparison = Util.stringToDate(budget.getDateCreated());

    if (currentDateForComparison.after(latestDateForComparison)) {
      budget.setDateCreated(Util.getCurrentDateTime());
      budgetsDao.createBudgetItem(budget);
    } else {
      budgetsDao.updateBudgetAmountSpent(budget);
    }
    return budget;
  }
コード例 #8
0
        @Override
        public void getChar(
            String oid,
            String type,
            String ip,
            String currency,
            String couponId,
            final CtFetchCallback<String> callback) {
          LogHelper.e(TAG, TextUtils.join("|", new String[] {oid, type, ip, currency, couponId}));
          OrderBusiness.getCharge(
              ((PayOrderAcivity) iPayOrderView),
              mClient,
              new LabAsyncHttpResponseHandler() {
                @Override
                public void onSuccess(LabResponse response, Object data) {
                  callback.onSuc(String.valueOf(data));
                }

                @Override
                public void onFailure(LabResponse response, Object data) {
                  String msg = response.msg;
                  if (TextUtils.isEmpty(msg)) {
                    msg = PlatformUtil.getInstance().getString(R.string.ct_pay_failed);
                  }
                  callback.onFailed(new CtException(msg));
                }
              },
              oid,
              type,
              ip,
              currency,
              couponId);
        }
コード例 #9
0
  private String getCustomValuesText(PDroidAppSetting setting) {
    if (setting.getCustomValues() != null && setting.getCustomValues().size() > 0) {
      List<String> customValueStrings = new LinkedList<String>();
      for (SimpleImmutableEntry<String, String> customValue : setting.getCustomValues()) {
        SpannableStringBuilder builder = new SpannableStringBuilder();
        if (customValue.getKey() != null && !(customValue.getKey().isEmpty())) {
          builder.append(customValue.getKey()).append(":");
        }
        if (customValue.getValue() != null && !(customValue.getValue().isEmpty())) {
          builder.append(customValue.getValue());
          builder.setSpan(
              new StyleSpan(Typeface.ITALIC),
              builder.length() - customValue.getValue().length(),
              builder.length(),
              0);
        }

        if (!builder.toString().isEmpty()) {
          customValueStrings.add(builder.toString());
        }
      }

      if (customValueStrings.size() > 0) {
        return TextUtils.join(
            context.getString(R.string.detail_custom_value_spacer), customValueStrings);
      }
    }
    return null;
  }
コード例 #10
0
  public void saveAvailability() {
    ViewGroup availGroup = (ViewGroup) findViewById(R.id.availability_list);
    ArrayList<String> availList = new ArrayList<String>();

    int availability = 0;
    int dayMask[] = getResources().getIntArray(R.array.availability_days_mask);
    int timeMask[] = getResources().getIntArray(R.array.availability_times_mask);

    for (int i = 0; i < availGroup.getChildCount(); i++) {
      int day =
          ((Spinner) availGroup.getChildAt(i).findViewWithTag("day")).getSelectedItemPosition();
      int time =
          ((Spinner) availGroup.getChildAt(i).findViewWithTag("time")).getSelectedItemPosition();

      availList.add(String.format(Locale.US, "%d,%d", day, time));
      availability |= dayMask[day] & timeMask[time];
    }

    try {
      mUser.put("availability", availability);
      mUser.put("availability_string", TextUtils.join(":", availList));
    } catch (JSONException e) {
      Log.e(TAG, e.toString());
    }
  }
コード例 #11
0
  public StringToNumberMatcher() {
    String[][] numbersVariant =
        new String[][] {
          {"ноль", "нуль"},
          {
            "один", "одного", "одному", "одним", "одном", "одна", "одной", "одну", "одних",
            "одними", "одни", "одною", "одно"
          },
          {"два", "двух", "двум", "двумя", "две", "пару", "паре"},
          {"три", "трем", "трех", "тремя"},
          {"четырех", "четырем", "четырьмя", "четыре"},
          {"пяти", "пятью", "пять"},
          {"шести", "шестью", "шесть"},
          {"семи", "семью", "семь"},
          {"восьми", "восьмью", "восемь"},
          {"девяти", "девятью", "девять"},
          {"десяти", "десятью", "десять"}
        };

    numbers = new Pattern[numbersVariant.length];

    for (int i = 0; i < numbersVariant.length; i++) {
      numbers[i] =
          Pattern.compile("([^а-я]|^)(" + TextUtils.join("|", numbersVariant[i]) + ")([^а-я]|$)");
    }
  }
コード例 #12
0
 /** First creates a record for each of the matches in this round before creating the round. */
 @Override
 public ContentValues toContentValues(LeagueRound round, ElifutPersistenceService service) {
   return ContentValuesBuilder.create()
       .put("round_number", round.roundNumber())
       .put("matches", TextUtils.join(",", Lists.transform(round.matches(), service::create)))
       .build();
 }
コード例 #13
0
  public MonthsMatcher() {
    // напомни в январе = 1.01
    monthNameList =
        new String[][] {
          {"числа"},
          {"январь", "января", "январе", "январи", "январей", "январях"},
          {"февраль", "февраля", "феврале", "феврали", "февралей", "февралях"},
          {"марта", "марте", "марты", "мартов", "мартах", "марту", "март"},
          {"апреля", "апреле", "апрели", "апрелей", "апрелях", "апрель"},
          {"мае", "майя", "майи", "майю", "май", "мая"},
          {"июни", "июней", "июнях", "июнь", "июня", "июне"},
          {"июлей", "июлях", "июль", "июля", "июле", "июли"},
          {"август", "августа", "августе", "августы", "августов", "августах", "августу"},
          {"сентябрь", "сентября", "сентябре", "сентябри", "сентябрей", "сентябрях"},
          {"октябрь", "октября", "октябре", "октябри", "октябрей", "октябрях"},
          {"ноябрь", "ноября", "ноябре", "ноябри", "ноябрей", "ноябрях"},
          {"декабря", "декабре", "декабри", "декабрей", "декабрях", "декабрь"}
        };

    Vector<String> monthNameAll = new Vector<String>();

    for (String[] aMonthNameList : monthNameList) {
      Collections.addAll(monthNameAll, aMonthNameList);
    }
    month =
        Pattern.compile(
            "(((^|[^0-9])[012]?\\d|30|31)\\s+|[^а-я]|^)("
                + TextUtils.join("|", monthNameAll)
                + ")([^а-я]|$)");
  }
コード例 #14
0
  @Override
  public boolean clearExpired(Date date) {
    boolean clearedAny = false;
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();

    for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) {
      String name = entry.getKey();
      Cookie cookie = entry.getValue();
      if (cookie.isExpired(date)) {
        // Clear cookies from local store
        cookies.remove(name);

        // Clear cookies from persistent store
        prefsWriter.remove(COOKIE_NAME_PREFIX + name);

        // We've cleared at least one
        clearedAny = true;
      }
    }

    // Update names in persistent store
    if (clearedAny) {
      prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
    }
    prefsWriter.commit();

    return clearedAny;
  }
コード例 #15
0
  private Request createRequest(
      Location location,
      int radiusInMeters,
      int resultsLimit,
      String searchText,
      Set<String> extraFields,
      Session session) {
    Request request =
        Request.newPlacesSearchRequest(
            session, location, radiusInMeters, resultsLimit, searchText, null);

    Set<String> fields = new HashSet<String>(extraFields);
    String[] requiredFields = new String[] {ID, NAME, LOCATION, CATEGORY, WERE_HERE_COUNT};
    fields.addAll(Arrays.asList(requiredFields));

    String pictureField = adapter.getPictureFieldSpecifier();
    if (pictureField != null) {
      fields.add(pictureField);
    }

    Bundle parameters = request.getParameters();
    parameters.putString("fields", TextUtils.join(",", fields));
    request.setParameters(parameters);

    return request;
  }
コード例 #16
0
 public void setVideoCodecList(List<String> codecs) {
   if (codecs != null) {
     setPreferenceStringValue(
         PreferencesWrapper.CODECS_VIDEO_LIST,
         TextUtils.join(PreferencesWrapper.CODECS_SEPARATOR, codecs));
   }
 }
コード例 #17
0
  public static ProxyStatusItem isProxyValidExclusionList(String[] proxyExclusionList) {
    try {
      for (int i = 0; i < proxyExclusionList.length; i++) {
        String s = proxyExclusionList[i].trim();
        ProxyStatusItem status = isProxyValidExclusionAddress(s);

        if (!status.result) {
          return new ProxyStatusItem(
              ProxyStatusProperties.PROXY_VALID_EXCLUSION_LIST,
              CheckStatusValues.CHECKED,
              true,
              APL.getContext().getString(R.string.status_exclusion_list_notvalid));
        }
      }

      String msg =
          String.format(
              "%s %s",
              APL.getContext().getString(R.string.status_exclusion_item_valid),
              TextUtils.join(",", proxyExclusionList));
      return new ProxyStatusItem(
          ProxyStatusProperties.PROXY_VALID_EXCLUSION_ITEM, CheckStatusValues.CHECKED, true, msg);
    } catch (Exception e) {
      APL.getEventReport().send(e);
    }

    return new ProxyStatusItem(
        ProxyStatusProperties.PROXY_VALID_EXCLUSION_ITEM,
        CheckStatusValues.CHECKED,
        false,
        APL.getContext().getString(R.string.status_exclusion_item_notvalid));
  }
コード例 #18
0
  /**
   * Internal method to handle single sign-on backend for authorize().
   *
   * @param activity The Android Activity that will parent the ProxyAuth Activity.
   * @param applicationId The Facebook application identifier.
   * @param permissions A list of permissions required for this application. If you do not require
   *     any permissions, pass an empty String array.
   * @param activityCode Activity code to uniquely identify the result Intent in the callback.
   */
  private boolean startSingleSignOn(
      Activity activity, String applicationId, String[] permissions, int activityCode) {
    boolean didSucceed = true;
    Intent intent = new Intent();

    intent.setClassName("com.facebook.katana", "com.facebook.katana.ProxyAuth");
    intent.putExtra("client_id", applicationId);
    if (permissions.length > 0) {
      intent.putExtra("scope", TextUtils.join(",", permissions));
    }

    // Verify that the application whose package name is
    // com.facebook.katana.ProxyAuth
    // has the expected FB app signature.
    if (!validateAppSignatureForIntent(activity, intent)) {
      return false;
    }

    mAuthActivity = activity;
    mAuthPermissions = permissions;
    mAuthActivityCode = activityCode;
    try {
      activity.startActivityForResult(intent, activityCode);
    } catch (ActivityNotFoundException e) {
      didSucceed = false;
    }

    return didSucceed;
  }
コード例 #19
0
ファイル: PrivacyProvider.java プロジェクト: kv1dr/XPrivacy
  private void updateRestriction(
      int uid, String restrictionName, String methodName, boolean allowed) {
    // Get restrictions
    SharedPreferences prefs =
        getContext().getSharedPreferences(PREF_RESTRICTION, Context.MODE_WORLD_READABLE);
    String restrictions = prefs.getString(getRestrictionPref(restrictionName), "*");

    // Decode restrictions
    List<String> listRestriction = new ArrayList<String>(Arrays.asList(restrictions.split(",")));
    boolean defaultAllowed = listRestriction.get(0).equals("*");

    // Allow or deny
    String sUid = Integer.toString(uid);
    if (defaultAllowed ? allowed : !allowed) listRestriction.remove(sUid);
    if (defaultAllowed ? !allowed : allowed)
      if (!listRestriction.contains(sUid)) listRestriction.add(sUid);

    // Encode restrictions
    restrictions = TextUtils.join(",", listRestriction.toArray(new String[0]));

    // Update restriction
    SharedPreferences.Editor editor = prefs.edit();
    if (methodName == null || !allowed)
      editor.putString(getRestrictionPref(restrictionName), restrictions);
    if (methodName != null)
      editor.putBoolean(getExceptionPref(uid, restrictionName, methodName), allowed);
    editor.apply();
    setPrefFileReadable(PREF_RESTRICTION);
  }
コード例 #20
0
  private void addLocalNetworksToRoutes() {

    // Add local network interfaces
    String[] localRoutes = NativeUtils.getIfconfig();

    // The format of mLocalRoutes is kind of broken because I don't really like JNI
    for (int i = 0; i < localRoutes.length; i += 3) {
      String intf = localRoutes[i];
      String ipAddr = localRoutes[i + 1];
      String netMask = localRoutes[i + 2];

      if (intf == null || intf.equals("lo") || intf.startsWith("tun") || intf.startsWith("rmnet"))
        continue;

      if (ipAddr == null || netMask == null) {
        VpnStatus.logError(
            "Local routes are broken?! (Report to author) " + TextUtils.join("|", localRoutes));
        continue;
      }

      if (ipAddr.equals(mLocalIP.mIp)) continue;

      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT && !mProfile.mAllowLocalLAN) {
        mRoutes.addIPSplit(new CIDRIP(ipAddr, netMask), true);

      } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && mProfile.mAllowLocalLAN)
        mRoutes.addIP(new CIDRIP(ipAddr, netMask), false);
    }
  }
コード例 #21
0
ファイル: VpnStatus.java プロジェクト: rajeshatit/VPN-Android
    public String getString(Context c) {
      try {
        if (mMessage != null) {
          return mMessage;
        } else {
          if (c != null) {
            if (mRessourceId == com.openvpn.Durai.R.string.mobile_info)
              return getMobileInfoString(c);
            if (mArgs == null) return c.getString(mRessourceId);
            else return c.getString(mRessourceId, mArgs);
          } else {
            String str = String.format(Locale.ENGLISH, "Log (no context) resid %d", mRessourceId);
            if (mArgs != null) str += TextUtils.join("|", mArgs);

            return str;
          }
        }
      } catch (UnknownFormatConversionException e) {
        if (c != null)
          throw new UnknownFormatConversionException(e.getLocalizedMessage() + getString(null));
        else throw e;
      } catch (java.util.FormatFlagsConversionMismatchException e) {
        if (c != null)
          throw new FormatFlagsConversionMismatchException(
              e.getLocalizedMessage() + getString(null), e.getConversion());
        else throw e;
      }
    }
コード例 #22
0
  // Note that this method makes a synchronous Graph API call, so should not be called from the main
  // thread.
  public static FetchedAppSettings queryAppSettings(
      final String applicationId, final boolean forceRequery) {

    // Cache the last app checked results.
    if (!forceRequery && fetchedAppSettings.containsKey(applicationId)) {
      return fetchedAppSettings.get(applicationId);
    }

    Bundle appSettingsParams = new Bundle();
    appSettingsParams.putString(APPLICATION_FIELDS, TextUtils.join(",", APP_SETTING_FIELDS));

    Request request = Request.newGraphPathRequest(null, applicationId, null);
    request.setParameters(appSettingsParams);

    GraphObject supportResponse = request.executeAndWait().getGraphObject();
    FetchedAppSettings result =
        new FetchedAppSettings(
            safeGetBooleanFromResponse(supportResponse, SUPPORTS_ATTRIBUTION),
            safeGetBooleanFromResponse(supportResponse, SUPPORTS_IMPLICIT_SDK_LOGGING),
            safeGetStringFromResponse(supportResponse, NUX_CONTENT),
            safeGetBooleanFromResponse(supportResponse, NUX_ENABLED));

    fetchedAppSettings.put(applicationId, result);

    return result;
  }
コード例 #23
0
 @Override
 void saveSelectionToBundle(Bundle outBundle, String key) {
   if (!selectedIds.isEmpty()) {
     String ids = TextUtils.join(",", selectedIds);
     outBundle.putString(key, ids);
   }
 }
コード例 #24
0
        @Override
        public void needCharge(
            String oid, String currency, String couponId, final CtFetchCallback<Boolean> callback) {
          LogHelper.e(TAG, TextUtils.join("|", new String[] {oid, currency, couponId}));
          OrderBusiness.getFinalPrice(
              ((PayOrderAcivity) iPayOrderView),
              mClient,
              new LabAsyncHttpResponseHandler() {
                @Override
                public void onSuccess(LabResponse response, Object data) {
                  LogHelper.e(TAG, " need char " + String.valueOf(response.result));
                  JSONObject jsonObject = JSONObject.parseObject(String.valueOf(data));
                  double value = 0;

                  try {
                    value = Double.valueOf(jsonObject.getString("finalPrice"));
                  } catch (NumberFormatException e) {
                    value = 1;
                  }
                  callback.onSuc(value > 0);
                }

                @Override
                public void onFailure(LabResponse response, Object data) {
                  String msg = response.msg;
                  if (TextUtils.isEmpty(msg)) {
                    msg = PlatformUtil.getInstance().getString(R.string.ct_pay_failed);
                  }
                  callback.onFailed(new CtException(msg));
                }
              },
              oid,
              currency,
              couponId);
        }
コード例 #25
0
ファイル: ContactList.java プロジェクト: sunfengbiao/MMS
 public String formatNamesAndNumbers(String separator) {
   String[] nans = new String[size()];
   int i = 0;
   for (Contact c : this) {
     nans[i++] = c.getNameAndNumber();
   }
   return TextUtils.join(separator, nans);
 }
コード例 #26
0
 /**
  * Builds the Uri by converting into a android.net.Uri object.
  *
  * @return a new android.net.Uri defined by what was given to the builder.
  */
 public Uri build() {
   return new Uri.Builder()
       .scheme(this.scheme)
       .authority(this.host)
       .path(this.path == null ? "" : this.path.toString())
       .encodedQuery(TextUtils.join("&", this.queryParameters))
       .build();
 }
コード例 #27
0
  public static void delete(Context context, String settingSetName) {
    Set<String> availableSets = getAvailableSettingSets(context);
    availableSets.remove(settingSetName);

    Editor editor = getMeta(context).edit();
    editor.putString(AVAILABLE_SETTINGS_SET, TextUtils.join(",", availableSets));
    editor.commit();
  }
コード例 #28
0
  @Override
  public void bindView(View view, Context context, Cursor cursor) {
    String teacher = cursor.getString(cursor.getColumnIndex(Lesson.TEACHER_ATTR));
    TextView teacherView = (TextView) view.findViewById(R.id.lesson_teacher_label);
    teacherView.setText(teacher);

    String title = cursor.getString(cursor.getColumnIndex(Lesson.SUBJ_ATTR));
    TextView titleView = (TextView) view.findViewById(R.id.lesson_title_label);
    titleView.setText(title);

    int timeIndex = cursor.getInt(cursor.getColumnIndex(Lesson.TIME_ATTR));
    String time = context.getResources().getStringArray(R.array.lessons_time)[timeIndex];
    TextView timeView = (TextView) view.findViewById(R.id.lesson_time_label);
    timeView.setText(time);

    List<String> params = new LinkedList<String>();

    String auditorium = cursor.getString(cursor.getColumnIndex(Lesson.AUDITORIUM_ATTR));
    if (!TextUtils.isEmpty(auditorium)) {
      params.add(
          String.format("%s %s", auditorium, context.getString(R.string.lesson_param_auditorium)));
    }

    int subgroupsBits = cursor.getInt(cursor.getColumnIndex(Lesson.SUBGROUP_ATTR));
    if (subgroupsBits != Lesson.ALL_SUBGROUPS) {
      String subgroups = TextUtils.join(",", BitUtil.decode(subgroupsBits));
      params.add(
          String.format("%s %s", subgroups, context.getString(R.string.lesson_param_subgroups)));
    }

    int weeksBits = cursor.getInt(cursor.getColumnIndex(Lesson.WEEKS_ATTR));
    if (weeksBits != Lesson.ALL_WEEKS) {
      String weeks = TextUtils.join(",", BitUtil.decode(weeksBits));
      params.add(String.format("%s %s", weeks, context.getString(R.string.lesson_param_weeks)));
    }

    String stringParams = TextUtils.join(" / ", params);
    TextView paramView = (TextView) view.findViewById(R.id.lesson_param_label);
    paramView.setText(stringParams);

    int lessonType = cursor.getInt(cursor.getColumnIndex(Lesson.TYPE_ATTR));
    View backgroundView = view.findViewById(R.id.lesson_item_background);
    String backgroundColor =
        context.getResources().getStringArray(R.array.lesson_type_colors)[lessonType];
    backgroundView.setBackgroundColor(Color.parseColor(backgroundColor));
  }
コード例 #29
0
  @Test
  public void underscore() {

    when(TextUtils.join("_", new String[] {"Hello", "World"})).thenReturn("Hello_World");

    assertEquals("hello_world", StringSupport.underscore("HelloWorld"));

    verifyStatic();
  }
コード例 #30
0
 @Override
 public RequestBuilder buildRequest(Api api) {
   RequestBuilder builder =
       api.action("query")
           .param("titles", TextUtils.join("|", titles))
           .param("continue", ""); // to avoid warning about new continuation syntax
   buildQueryParams(builder);
   return builder;
 }