コード例 #1
1
  List<List<MonthCellDescriptor>> getMonthCells(MonthDescriptor month, Calendar startCal) {
    Calendar cal = Calendar.getInstance(locale);
    cal.setTime(startCal.getTime());
    List<List<MonthCellDescriptor>> cells = new ArrayList<List<MonthCellDescriptor>>();
    cal.set(DAY_OF_MONTH, 1);
    int firstDayOfWeek = cal.get(DAY_OF_WEEK);
    int offset = cal.getFirstDayOfWeek() - firstDayOfWeek;
    if (offset > 0) {
      offset -= 7;
    }
    cal.add(Calendar.DATE, offset);

    Calendar minSelectedCal = minDate(selectedCals);
    Calendar maxSelectedCal = maxDate(selectedCals);

    while ((cal.get(MONTH) < month.getMonth() + 1 || cal.get(YEAR) < month.getYear()) //
        && cal.get(YEAR) <= month.getYear()) {
      Logr.d("Building week row starting at %s", cal.getTime());
      List<MonthCellDescriptor> weekCells = new ArrayList<MonthCellDescriptor>();
      cells.add(weekCells);
      for (int c = 0; c < 7; c++) {
        Date date = cal.getTime();
        boolean isCurrentMonth = cal.get(MONTH) == month.getMonth();
        boolean isSelected = isCurrentMonth && containsDate(selectedCals, cal);
        boolean isSelectable =
            isCurrentMonth && betweenDates(cal, minCal, maxCal) && isDateSelectable(date);
        boolean isToday = sameDate(cal, today);
        boolean isHighlighted = containsDate(highlightedCals, cal);
        int value = cal.get(DAY_OF_MONTH);

        MonthCellDescriptor.RangeState rangeState = MonthCellDescriptor.RangeState.NONE;
        if (selectedCals.size() > 1) {
          if (sameDate(minSelectedCal, cal)) {
            rangeState = MonthCellDescriptor.RangeState.FIRST;
          } else if (sameDate(maxDate(selectedCals), cal)) {
            rangeState = MonthCellDescriptor.RangeState.LAST;
          } else if (betweenDates(cal, minSelectedCal, maxSelectedCal)) {
            rangeState = MonthCellDescriptor.RangeState.MIDDLE;
          }
        }

        weekCells.add(
            new MonthCellDescriptor(
                date,
                isCurrentMonth,
                isSelectable,
                isSelected,
                isToday,
                isHighlighted,
                value,
                rangeState));
        cal.add(DATE, 1);
      }
    }
    return cells;
  }
コード例 #2
0
 private static Calendar maxDate(List<Calendar> selectedCals) {
   if (selectedCals == null || selectedCals.size() == 0) {
     return null;
   }
   Collections.sort(selectedCals);
   return selectedCals.get(selectedCals.size() - 1);
 }
コード例 #3
0
 @Override
 public int getPositionForSection(int section) {
   if (displaySections) {
     section = Math.max(0, Math.min(section, sectionKeys.size() - 1));
     if (section < sectionKeys.size()) {
       return getPosition(sectionKeys.get(section), null);
     }
   }
   return 0;
 }
コード例 #4
0
  private void updateLocalVersions() {
    if (NavigineApp.Navigation == null) return;

    for (int i = 0; i < mInfoList.size(); ++i) {
      LocationInfo info = mInfoList.get(i);
      String versionStr = LocationLoader.getLocalVersion(NavigineApp.AppContext, info.title);
      if (versionStr != null) {
        // Log.d(TAG, info.title + ": " + versionStr);
        info.localModified = versionStr.endsWith("+");
        if (info.localModified) versionStr = versionStr.substring(0, versionStr.length() - 1);
        try {
          info.localVersion = Integer.parseInt(versionStr);
        } catch (Throwable e) {
        }
      } else {
        info.localVersion = -1;

        String mapFile = NavigineApp.Settings.getString("map_file", "");
        if (mapFile.equals(info.archiveFile)) {
          NavigineApp.Navigation.loadArchive(null);
          SharedPreferences.Editor editor = NavigineApp.Settings.edit();
          editor.putString("map_file", "");
          editor.commit();
        }
      }
    }
    mAdapter.updateList();
  }
コード例 #5
0
  public void prioritizeViewRange(int firstVisibleItem, int lastVisibleItem, int prefetchBuffer) {
    if ((lastVisibleItem < firstVisibleItem) || (sectionKeys.size() == 0)) {
      return;
    }

    // We want to prioritize requests for items which are visible but do not have pictures
    // loaded yet. We also want to pre-fetch pictures for items which are not yet visible
    // but are within a buffer on either side of the visible items, on the assumption that
    // they will be visible soon. For these latter items, we'll store the images in memory
    // in the hopes we can immediately populate their image view when needed.

    // Prioritize the requests in reverse order since each call to prioritizeRequest will just
    // move it to the front of the queue. And we want the earliest ones in the range to be at
    // the front of the queue, so all else being equal, the list will appear to populate from
    // the top down.
    for (int i = lastVisibleItem; i >= 0; i--) {
      SectionAndItem<T> sectionAndItem = getSectionAndItem(i);
      if (sectionAndItem.graphObject != null) {
        String id = getIdOfGraphObject(sectionAndItem.graphObject);
        ImageRequest request = pendingRequests.get(id);
        if (request != null) {
          ImageDownloader.prioritizeRequest(request);
        }
      }
    }

    // For items which are not visible, but within the buffer on either side, we want to
    // fetch those items and store them in a small in-memory cache of bitmaps.
    int start = Math.max(0, firstVisibleItem - prefetchBuffer);
    int end = Math.min(lastVisibleItem + prefetchBuffer, getCount() - 1);
    ArrayList<T> graphObjectsToPrefetchPicturesFor = new ArrayList<T>();
    // Add the IDs before and after the visible range.
    for (int i = start; i < firstVisibleItem; ++i) {
      SectionAndItem<T> sectionAndItem = getSectionAndItem(i);
      if (sectionAndItem.graphObject != null) {
        graphObjectsToPrefetchPicturesFor.add(sectionAndItem.graphObject);
      }
    }
    for (int i = lastVisibleItem + 1; i <= end; ++i) {
      SectionAndItem<T> sectionAndItem = getSectionAndItem(i);
      if (sectionAndItem.graphObject != null) {
        graphObjectsToPrefetchPicturesFor.add(sectionAndItem.graphObject);
      }
    }
    for (T graphObject : graphObjectsToPrefetchPicturesFor) {
      URI uri = getPictureUriOfGraphObject(graphObject);
      final String id = getIdOfGraphObject(graphObject);

      // This URL already have been requested for pre-fetching, but we want to act in an LRU manner,
      // so move
      // it to the end of the list regardless.
      boolean alreadyPrefetching = prefetchedProfilePictureIds.remove(id);
      prefetchedProfilePictureIds.add(id);

      // If we've already requested it for pre-fetching, no need to do so again.
      if (!alreadyPrefetching) {
        downloadProfilePicture(id, uri, null);
      }
    }
  }
コード例 #6
0
  SectionAndItem<T> getSectionAndItem(int position) {
    if (sectionKeys.size() == 0) {
      return null;
    }
    String sectionKey = null;
    T graphObject = null;

    if (!displaySections) {
      sectionKey = sectionKeys.get(0);
      List<T> section = graphObjectsBySection.get(sectionKey);
      if (position >= 0 && position < section.size()) {
        graphObject = graphObjectsBySection.get(sectionKey).get(position);
      } else {
        // We are off the end; we must be adding an activity circle to indicate more data is coming.
        assert dataNeededListener != null && cursor.areMoreObjectsAvailable();
        // We return null for both to indicate this.
        return new SectionAndItem<T>(null, null);
      }
    } else {
      // Count through the sections; the "0" position in each section is the header. We decrement
      // position each time we skip forward a certain number of elements, including the header.
      for (String key : sectionKeys) {
        // Decrement if we skip over the header
        if (position-- == 0) {
          sectionKey = key;
          break;
        }

        List<T> section = graphObjectsBySection.get(key);
        if (position < section.size()) {
          // The position is somewhere in this section. Get the corresponding graph object.
          sectionKey = key;
          graphObject = section.get(position);
          break;
        }
        // Decrement by as many items as we skipped over
        position -= section.size();
      }
    }
    if (sectionKey != null) {
      // Note: graphObject will be null if this represents a section header.
      return new SectionAndItem<T>(sectionKey, graphObject);
    } else {
      throw new IndexOutOfBoundsException("position");
    }
  }
コード例 #7
0
 @Override
 public int getSectionForPosition(int position) {
   SectionAndItem<T> sectionAndItem = getSectionAndItem(position);
   if (sectionAndItem != null && sectionAndItem.getType() != SectionAndItem.Type.ACTIVITY_CIRCLE) {
     return Math.max(
         0, Math.min(sectionKeys.indexOf(sectionAndItem.sectionKey), sectionKeys.size() - 1));
   }
   return 0;
 }
コード例 #8
0
  @Override
  public int getCount() {
    if (sectionKeys.size() == 0) {
      return 0;
    }

    // If we are not displaying sections, we don't display a header; otherwise, we have one header
    // per item in
    // addition to the actual items.
    int count = (displaySections) ? sectionKeys.size() : 0;
    for (List<T> section : graphObjectsBySection.values()) {
      count += section.size();
    }

    // If we should show a cell with an activity circle indicating more data is coming, add it to
    // the count.
    if (shouldShowActivityCircleCell()) {
      ++count;
    }

    return count;
  }
コード例 #9
0
  private void rebuildSections() {
    sectionKeys = new ArrayList<String>();
    graphObjectsBySection = new HashMap<String, ArrayList<T>>();
    graphObjectsById = new HashMap<String, T>();
    displaySections = false;

    if (cursor == null || cursor.getCount() == 0) {
      return;
    }

    int objectsAdded = 0;
    cursor.moveToFirst();
    do {
      T graphObject = cursor.getGraphObject();

      if (!filterIncludesItem(graphObject)) {
        continue;
      }

      objectsAdded++;

      String sectionKeyOfItem = getSectionKeyOfGraphObject(graphObject);
      if (!graphObjectsBySection.containsKey(sectionKeyOfItem)) {
        sectionKeys.add(sectionKeyOfItem);
        graphObjectsBySection.put(sectionKeyOfItem, new ArrayList<T>());
      }
      List<T> section = graphObjectsBySection.get(sectionKeyOfItem);
      section.add(graphObject);

      graphObjectsById.put(getIdOfGraphObject(graphObject), graphObject);
    } while (cursor.moveToNext());

    if (sortFields != null) {
      final Collator collator = Collator.getInstance();
      for (List<T> section : graphObjectsBySection.values()) {
        Collections.sort(
            section,
            new Comparator<GraphObject>() {
              @Override
              public int compare(GraphObject a, GraphObject b) {
                return compareGraphObjects(a, b, sortFields, collator);
              }
            });
      }
    }

    Collections.sort(sectionKeys, Collator.getInstance());

    displaySections = sectionKeys.size() > 1 && objectsAdded > DISPLAY_SECTIONS_THRESHOLD;
  }
コード例 #10
0
ファイル: D4.java プロジェクト: sarekautowerke/D4
  public void getFilesFromFolder(List filesAndFolders, String savePath) {
    // create a File object for the parent directory
    File downloadsDirectory = new File(savePath);
    // create the folder if needed.
    downloadsDirectory.mkdir();

    for (int i = 0; i < filesAndFolders.size(); i++) {
      Object links = filesAndFolders.get(i);
      List linksArray = (ArrayList) links;
      if (i == 0) {
        for (int j = 0; j < linksArray.size(); j += 2) {
          // We've got an array of file urls so download each one to a directory with the folder
          // name
          String fileURL = linksArray.get(j).toString();
          String fileName = linksArray.get(j + 1).toString();
          downloadFile(fileURL, savePath, fileName);
          progress++;
          Message msg = mHandler.obtainMessage();
          msg.arg1 = progress;
          mHandler.sendMessage(msg);
        }
      } else if (i == 1) {
        // we've got an array of folders so recurse down the levels, extracting subfolders and files
        // until we've downloaded everything.
        for (int j = 0; j < linksArray.size(); j += 2) {
          String folderURL = linksArray.get(j).toString();
          String folderName = linksArray.get(j + 1).toString();

          String page = getData(folderURL);
          List newFilesAndFolders = parsePage(page);
          String dlDirPath = savePath + folderName + "/";

          getFilesFromFolder(newFilesAndFolders, dlDirPath);
        }
      }
    }
  }
コード例 #11
0
  @Override
  protected void onStart() {
    super.onStart();

    myAllItems.clear();

    final Intent intent = getIntent();

    myAllItems.add(new SectionItem("enabled"));
    final List<String> enabledIds =
        intent.getStringArrayListExtra(NetworkLibraryActivity.ENABLED_CATALOG_IDS_KEY);
    if (enabledIds.size() > 0) {
      final TreeSet<CatalogItem> cItems = new TreeSet<CatalogItem>();
      for (String id : enabledIds) {
        final NetworkTree tree = NetworkLibrary.Instance().getCatalogTreeByUrlAll(id);
        if (tree != null && tree.getLink() != null) {
          cItems.add(new CatalogItem(id, true, tree));
        }
      }
      myAllItems.addAll(cItems);
      mySelectedItems.addAll(cItems);
    }

    myAllItems.add(new SectionItem("disabled"));
    final List<String> disabledIds =
        intent.getStringArrayListExtra(NetworkLibraryActivity.DISABLED_CATALOG_IDS_KEY);
    if (disabledIds.size() > 0) {
      final TreeSet<CatalogItem> cItems = new TreeSet<CatalogItem>();
      for (String id : disabledIds) {
        cItems.add(
            new CatalogItem(id, false, NetworkLibrary.Instance().getCatalogTreeByUrlAll(id)));
      }
      myAllItems.addAll(cItems);
    }

    setListAdapter(new CatalogsListAdapter());
  }
コード例 #12
0
ファイル: GpsMainActivity.java プロジェクト: pari-m/gpslogger
  private void UploadToDropBox() {
    Utilities.LogDebug("GpsMainActivity.UploadToDropBox");

    final DropBoxHelper dropBoxHelper = new DropBoxHelper(getApplicationContext(), this);

    if (!dropBoxHelper.IsLinked()) {
      startActivity(new Intent("com.mendhak.gpslogger.DROPBOX_SETUP"));
      return;
    }

    final File gpxFolder = new File(Environment.getExternalStorageDirectory(), "GPSLogger");

    if (gpxFolder.exists()) {

      String[] enumeratedFiles = gpxFolder.list();
      List<String> fileList = new ArrayList<String>(Arrays.asList(enumeratedFiles));
      Collections.reverse(fileList);
      final String[] files = fileList.toArray(new String[fileList.size()]);

      final Dialog dialog = new Dialog(this);
      dialog.setTitle(R.string.dropbox_upload);
      dialog.setContentView(R.layout.filelist);
      ListView thelist = (ListView) dialog.findViewById(R.id.listViewFiles);

      thelist.setAdapter(
          new ArrayAdapter<String>(
              getApplicationContext(), android.R.layout.simple_list_item_single_choice, files));

      thelist.setOnItemClickListener(
          new OnItemClickListener() {

            public void onItemClick(AdapterView<?> av, View v, int index, long arg) {

              dialog.dismiss();
              String chosenFileName = files[index];
              Utilities.ShowProgress(
                  GpsMainActivity.this,
                  getString(R.string.dropbox_uploading),
                  getString(R.string.please_wait));
              dropBoxHelper.UploadFile(chosenFileName);
            }
          });
      dialog.show();
    } else {
      Utilities.MsgBox(getString(R.string.sorry), getString(R.string.no_files_found), this);
    }
  }
コード例 #13
0
ファイル: GpuSGX540.java プロジェクト: kshark27/Kernel-Tuner
  @Override
  public void onCreate(Bundle savedInstanceState) {
    c = this;
    preferences = PreferenceManager.getDefaultSharedPreferences(c);

    super.onCreate(savedInstanceState);

    setContentView(R.layout.gpu_sgx540);

    gpuCurrent = readFile(Constants.GPU_SGX540);
    seekGpu = (SeekBar) findViewById(R.id.seek_gpu);

    gpu = Arrays.asList(153, 307, 384);
    seekBar(gpu.size() - 1, gpu.indexOf(gpuCurrent));

    /*else{
    seekGpu.setEnabled(false);
    seekIva.setEnabled(false);
    TextView ns = (TextView)findViewById(R.id.not_supported);
    ns.setVisibility(View.VISIBLE);
    }*/
    preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    curGpuTxt = (TextView) findViewById(R.id.current_gpu);
    maxGpuTxt = (TextView) findViewById(R.id.max_gpu);
    minGpuTxt = (TextView) findViewById(R.id.min_gpu);

    mhz = getResources().getString(R.string.mhz);
    current = getResources().getString(R.string.current);
    max = getResources().getString(R.string._max);
    min = getResources().getString(R.string._min);
    curGpuTxt.setText(current + ": " + (gpuCurrent) + mhz);
    maxGpuTxt.setText(max + ": " + gpu.get(2) + mhz);
    minGpuTxt.setText(min + ": " + gpu.get(0) + mhz);

    Button cancel = (Button) findViewById(R.id.cancel);
    cancel.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View arg0) {
            finish();
          }
        });
  }
コード例 #14
0
 private void scrollToSelectedDates() {
   Integer selectedIndex = null;
   Integer todayIndex = null;
   Calendar today = Calendar.getInstance(locale);
   for (int c = 0; c < months.size(); c++) {
     MonthDescriptor month = months.get(c);
     if (selectedIndex == null) {
       for (Calendar selectedCal : selectedCals) {
         if (sameMonth(selectedCal, month)) {
           selectedIndex = c;
           break;
         }
       }
       if (selectedIndex == null && todayIndex == null && sameMonth(today, month)) {
         todayIndex = c;
       }
     }
   }
   if (selectedIndex != null) {
     scrollToSelectedMonth(selectedIndex);
   } else if (todayIndex != null) {
     scrollToSelectedMonth(todayIndex);
   }
 }
コード例 #15
0
  /** Initializes "select account" spinner with existing accounts. */
  private void initAccountSpinner() {
    Spinner accountsSpiner = (Spinner) findViewById(R.id.selectAccountSpinner);

    Iterator<ProtocolProviderService> providers = AccountUtils.getRegisteredProviders().iterator();

    List<AccountID> accounts = new ArrayList<AccountID>();

    int selectedIdx = -1;
    int idx = 0;

    while (providers.hasNext()) {
      ProtocolProviderService provider = providers.next();

      OperationSet opSet = provider.getOperationSet(OperationSetPresence.class);

      if (opSet == null) continue;

      AccountID account = provider.getAccountID();
      accounts.add(account);
      idx++;

      if (account.isPreferredProvider()) {
        selectedIdx = idx;
      }
    }

    AccountsListAdapter accountsAdapter =
        new AccountsListAdapter(
            this, R.layout.select_account_row, R.layout.select_account_dropdown, accounts, true);
    accountsSpiner.setAdapter(accountsAdapter);

    // if we have only select account option and only one account
    // select the available account
    if (accounts.size() == 1) accountsSpiner.setSelection(0);
    else accountsSpiner.setSelection(selectedIdx);
  }
コード例 #16
0
 public final int getCount() {
   return myCurrentBook ? myBookmarks.size() + 1 : myBookmarks.size();
 }
コード例 #17
0
 @Override
 public boolean isEmpty() {
   // We'll never populate sectionKeys unless we have at least one object.
   return sectionKeys.size() == 0;
 }
コード例 #18
0
ファイル: GpsMainActivity.java プロジェクト: pari-m/gpslogger
  /** Uploads a GPS Trace to OpenStreetMap.org. */
  private void UploadToOpenStreetMap() {
    Utilities.LogDebug("GpsMainactivity.UploadToOpenStreetMap");

    if (!OSMHelper.IsOsmAuthorized(getApplicationContext())) {
      startActivity(OSMHelper.GetOsmSettingsIntent(getApplicationContext()));
      return;
    }

    final String goToOsmSettings = getString(R.string.menu_settings);

    final File gpxFolder = new File(Environment.getExternalStorageDirectory(), "GPSLogger");

    if (gpxFolder.exists()) {
      FilenameFilter select =
          new FilenameFilter() {

            public boolean accept(File dir, String filename) {
              return filename.toLowerCase().contains(".gpx");
            }
          };

      String[] enumeratedFiles = gpxFolder.list(select);
      List<String> fileList = new ArrayList<String>(Arrays.asList(enumeratedFiles));
      Collections.reverse(fileList);
      fileList.add(0, goToOsmSettings);
      final String[] files = fileList.toArray(new String[fileList.size()]);

      final Dialog dialog = new Dialog(this);
      dialog.setTitle(R.string.osm_pick_file);
      dialog.setContentView(R.layout.filelist);
      ListView thelist = (ListView) dialog.findViewById(R.id.listViewFiles);

      thelist.setAdapter(
          new ArrayAdapter<String>(
              getApplicationContext(), android.R.layout.simple_list_item_single_choice, files));

      thelist.setOnItemClickListener(
          new OnItemClickListener() {

            public void onItemClick(AdapterView<?> av, View v, int index, long arg) {

              dialog.dismiss();
              String chosenFileName = files[index];

              if (chosenFileName.equalsIgnoreCase(goToOsmSettings)) {
                startActivity(OSMHelper.GetOsmSettingsIntent(getApplicationContext()));
              } else {
                OSMHelper osm = new OSMHelper(GpsMainActivity.this, GpsMainActivity.this);
                Utilities.ShowProgress(
                    GpsMainActivity.this,
                    getString(R.string.osm_uploading),
                    getString(R.string.please_wait));
                osm.UploadGpsTrace(chosenFileName);
              }
            }
          });
      dialog.show();
    } else {
      Utilities.MsgBox(getString(R.string.sorry), getString(R.string.no_files_found), this);
    }
  }
コード例 #19
0
ファイル: GpsMainActivity.java プロジェクト: pari-m/gpslogger
  /**
   * Allows user to send a GPX/KML file along with location, or location only using a provider.
   * 'Provider' means any application that can accept such an intent (Facebook, SMS, Twitter, Email,
   * K-9, Bluetooth)
   */
  private void Share() {
    Utilities.LogDebug("GpsMainActivity.Share");
    try {

      final String locationOnly = getString(R.string.sharing_location_only);
      final File gpxFolder = new File(Environment.getExternalStorageDirectory(), "GPSLogger");
      if (gpxFolder.exists()) {
        String[] enumeratedFiles = gpxFolder.list();
        List<String> fileList = new ArrayList<String>(Arrays.asList(enumeratedFiles));
        Collections.reverse(fileList);
        fileList.add(0, locationOnly);
        final String[] files = fileList.toArray(new String[fileList.size()]);

        final Dialog dialog = new Dialog(this);
        dialog.setTitle(R.string.sharing_pick_file);
        dialog.setContentView(R.layout.filelist);
        ListView thelist = (ListView) dialog.findViewById(R.id.listViewFiles);

        thelist.setAdapter(
            new ArrayAdapter<String>(
                getApplicationContext(), android.R.layout.simple_list_item_single_choice, files));

        thelist.setOnItemClickListener(
            new OnItemClickListener() {

              public void onItemClick(AdapterView<?> av, View v, int index, long arg) {
                dialog.dismiss();
                String chosenFileName = files[index];

                final Intent intent = new Intent(Intent.ACTION_SEND);

                // intent.setType("text/plain");
                intent.setType("*/*");

                if (chosenFileName.equalsIgnoreCase(locationOnly)) {
                  intent.setType("text/plain");
                }

                intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.sharing_mylocation));
                if (Session.hasValidLocation()) {
                  String bodyText =
                      getString(
                          R.string.sharing_latlong_text,
                          String.valueOf(Session.getCurrentLatitude()),
                          String.valueOf(Session.getCurrentLongitude()));
                  intent.putExtra(Intent.EXTRA_TEXT, bodyText);
                  intent.putExtra("sms_body", bodyText);
                }

                if (chosenFileName.length() > 0 && !chosenFileName.equalsIgnoreCase(locationOnly)) {
                  intent.putExtra(
                      Intent.EXTRA_STREAM, Uri.fromFile(new File(gpxFolder, chosenFileName)));
                }

                startActivity(Intent.createChooser(intent, getString(R.string.sharing_via)));
              }
            });
        dialog.show();
      } else {
        Utilities.MsgBox(getString(R.string.sorry), getString(R.string.no_files_found), this);
      }
    } catch (Exception ex) {
      Utilities.LogError("Share", ex);
    }
  }
コード例 #20
0
  public void nextLevel() {
    boolean loaded = false;
    final GameBoard boardView = (GameBoard) this.findViewById(R.id.gameBoard);
    this.level++;

    AssetManager am = getResources().getAssets();

    try {
      List<String> allTutoLevels =
          new LinkedList<String>(Arrays.asList(am.list("levels/tutorial")));

      // if(addMsg){
      //    allTutoLevels.addAll(Arrays.asList(am.list("msg")));
      // }

      Log.d(TAG, allTutoLevels.toString());

      for (String name : allTutoLevels) {
        if (name.startsWith(this.level + ".")) {
          BufferedReader br =
              new BufferedReader(new InputStreamReader(am.open("levels/tutorial/" + name)));
          String line;
          String levelJSON = "";

          while ((line = br.readLine()) != null) {
            levelJSON += line + "\n";
          }

          br.close();

          game.initGame(
              levelJSON, boardView.getMeasuredWidth() / 60, boardView.getMeasuredHeight() / 60);
          loaded = true;
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    if (!loaded) {
      Random r = new Random();

      List<String> allLevels = new ArrayList<>();

      try {
        allLevels = Arrays.asList(am.list("levels"));
      } catch (IOException e) {
      }

      if (r.nextBoolean() && !allLevels.isEmpty() && allLevels.size() != allDoneLevels.size()) {
        try {
          int nLevel;
          do {
            nLevel = r.nextInt(allLevels.size());
          } while (allDoneLevels.contains(allLevels.get(nLevel)));

          String name = allLevels.get(nLevel);
          BufferedReader br = new BufferedReader(new InputStreamReader(am.open("levels/" + name)));

          String line;
          String levelJSON = "";

          while ((line = br.readLine()) != null) {
            levelJSON += line + "\n";
          }

          br.close();

          allDoneLevels.add(name);

          game.initGame(
              levelJSON, boardView.getMeasuredWidth() / 60, boardView.getMeasuredHeight() / 60);
        } catch (IOException e) {
          this.game.initGame(
              level, boardView.getMeasuredWidth() / 60, boardView.getMeasuredHeight() / 60);
        }
      } else {
        this.game.initGame(
            level, boardView.getMeasuredWidth() / 60, boardView.getMeasuredHeight() / 60);
      }
    }

    // am.close();

    boardView.setGame(this.game);
    boardView.invalidate();
    boardView.getHowdyShadeView().invalidate();

    Toast.makeText(this, this.level + "", Toast.LENGTH_SHORT).show();

    Log.i(
        TAG,
        "Max tiles : "
            + (boardView.getMeasuredWidth() / 60) * (boardView.getMeasuredHeight() / 60));
  }
コード例 #21
0
 @Override
 public final int getCount() {
   return myShowAddBookmarkItem ? myBookmarks.size() + 1 : myBookmarks.size();
 }
コード例 #22
0
  private boolean doSelectDate(Date date, MonthCellDescriptor cell) {
    Calendar newlySelectedCal = Calendar.getInstance(locale);
    newlySelectedCal.setTime(date);
    // Sanitize input: clear out the hours/minutes/seconds/millis.
    setMidnight(newlySelectedCal);

    // Clear any remaining range state.
    for (MonthCellDescriptor selectedCell : selectedCells) {
      selectedCell.setRangeState(RangeState.NONE);
    }

    switch (selectionMode) {
      case RANGE:
        if (selectedCals.size() > 1) {
          // We've already got a range selected: clear the old one.
          clearOldSelections();
        } else if (selectedCals.size() == 1 && newlySelectedCal.before(selectedCals.get(0))) {
          // We're moving the start of the range back in time: clear the
          // old start date.
          clearOldSelections();
        }
        break;

      case MULTIPLE:
        date = applyMultiSelect(date, newlySelectedCal);
        break;

      case SINGLE:
        clearOldSelections();
        break;
      default:
        throw new IllegalStateException("Unknown selectionMode " + selectionMode);
    }

    if (date != null) {
      // Select a new cell.
      if (selectedCells.size() == 0 || !selectedCells.get(0).equals(cell)) {
        selectedCells.add(cell);
        cell.setSelected(true);
      }
      selectedCals.add(newlySelectedCal);

      if (selectionMode == SelectionMode.RANGE && selectedCells.size() > 1) {
        // Select all days in between start and end.
        Date start = selectedCells.get(0).getDate();
        Date end = selectedCells.get(1).getDate();
        selectedCells.get(0).setRangeState(MonthCellDescriptor.RangeState.FIRST);
        selectedCells.get(1).setRangeState(MonthCellDescriptor.RangeState.LAST);

        for (List<List<MonthCellDescriptor>> month : cells) {
          for (List<MonthCellDescriptor> week : month) {
            for (MonthCellDescriptor singleCell : week) {
              if (singleCell.getDate().after(start)
                  && singleCell.getDate().before(end)
                  && singleCell.isSelectable()) {
                singleCell.setSelected(true);
                singleCell.setRangeState(MonthCellDescriptor.RangeState.MIDDLE);
                selectedCells.add(singleCell);
              }
            }
          }
        }
      }
    }

    // Update the adapter.
    validateAndUpdate();
    return date != null;
  }
コード例 #23
0
 public Date getSelectedDate() {
   return (selectedCals.size() > 0 ? selectedCals.get(0).getTime() : null);
 }