Example usage for android.text.format Formatter formatFileSize

List of usage examples for android.text.format Formatter formatFileSize

Introduction

In this page you can find the example usage for android.text.format Formatter formatFileSize.

Prototype

public static String formatFileSize(@Nullable Context context, long sizeBytes) 

Source Link

Document

Formats a content size to be in the form of bytes, kilobytes, megabytes, etc.

Usage

From source file:org.namelessrom.devicecontrol.modules.filepicker.FileAdapter.java

@Override
public View getView(final int position, View v, final ViewGroup parent) {
    final ViewHolder viewHolder;
    if (v == null) {
        v = LayoutInflater.from(context).inflate(R.layout.list_item_file, parent, false);
        assert (v != null);
        viewHolder = new ViewHolder(v);
        v.setTag(viewHolder);/* w ww. ja  v a  2s  .c  o m*/
    } else {
        viewHolder = (ViewHolder) v.getTag();
    }

    final File file = files.get(position);

    // we need to hack here as sometimes ../ is not properly recognized as directory
    final boolean isDirectory = file.isDirectory() || (file.getAbsolutePath() + File.separator).endsWith("../");

    viewHolder.rootView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (listener != null) {
                if (isDirectory) {
                    listener.onFilePicked(file);
                } else {
                    listener.onFlashItemPicked(new FlashItem(file.getAbsolutePath()));
                }
            }
        }
    });

    int color = AppResources.get().isDarkTheme() ? Color.WHITE : Color.BLACK;

    viewHolder.name.setText(file.getName());

    if (isDirectory) {
        viewHolder.icon.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_folder));
        viewHolder.info.setText(String.valueOf(new Date(file.lastModified())));
    } else {
        viewHolder.icon.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_file));
        viewHolder.info.setText(String.valueOf(new Date(file.lastModified())) + " | "
                + Formatter.formatFileSize(context, file.length()));

        // Color the list entry if a filetype is set, to make searching easier
        if (ContentTypes.isFiletypeMatching(file, fileType)) {
            if (colorResId > 0) {
                color = colorResId;
            } else {
                color = context.getResources().getColor(R.color.grass);
            }
        }
    }

    viewHolder.name.setTextColor(color);
    viewHolder.info.setTextColor(context.getResources().getColor(R.color.blueish_strong));
    viewHolder.icon.setColorFilter(Color.parseColor("#FFFFFF"));
    viewHolder.icon.setColorFilter(color);

    return v;
}

From source file:org.proninyaroslav.libretorrent.adapters.TorrentListAdapter.java

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    TorrentStateParcel state = currentItems.get(position).getState();

    Utils.setBackground(holder.indicatorCurOpenTorrent,
            ContextCompat.getDrawable(context, android.R.color.transparent));

    if (isSelected(position)) {
        Utils.setBackground(holder.itemTorrentList,
                ContextCompat.getDrawable(context, R.drawable.default_gray_rect));
    } else {/*  w  w  w.  ja v  a2s  .  co  m*/
        Utils.setBackground(holder.itemTorrentList,
                ContextCompat.getDrawable(context, R.drawable.default_rect_ripple));
    }

    holder.name.setText(state.name);

    holder.progress.setProgress(state.progress);

    String stateString = "";
    switch (state.stateCode) {
    case DOWNLOADING:
        stateString = context.getString(R.string.torrent_status_downloading);
        break;
    case SEEDING:
        stateString = context.getString(R.string.torrent_status_seeding);
        break;
    case PAUSED:
        stateString = context.getString(R.string.torrent_status_paused);
        break;
    case STOPPED:
        stateString = context.getString(R.string.torrent_status_stopped);
        break;
    case FINISHED:
        stateString = context.getString(R.string.torrent_status_finished);
        break;
    case CHECKING:
        stateString = context.getString(R.string.torrent_status_checking);
        break;
    }
    holder.state.setText(stateString);

    String counterTemplate = context.getString(R.string.download_counter_template);
    String totalBytes = Formatter.formatFileSize(context, state.totalBytes);
    String receivedBytes;
    if (state.progress == 100) {
        receivedBytes = totalBytes;
    } else {
        receivedBytes = Formatter.formatFileSize(context, state.receivedBytes);
    }

    holder.downloadCounter.setText(String.format(counterTemplate, receivedBytes, totalBytes, state.progress));

    String speedTemplate = context.getString(R.string.download_upload_speed_template);
    String downloadSpeed = Formatter.formatFileSize(context, state.downloadSpeed);
    String uploadSpeed = Formatter.formatFileSize(context, state.uploadSpeed);
    holder.downloadUploadSpeed.setText(String.format(speedTemplate, downloadSpeed, uploadSpeed));

    String ETA;
    if (state.ETA == -1) {
        ETA = Utils.INFINITY_SYMBOL;
    } else if (state.ETA == 0) {
        ETA = " ";
    } else {
        ETA = DateUtils.formatElapsedTime(state.ETA);
    }
    holder.ETA.setText(ETA);

    holder.pauseButton.setStartDrawable(R.drawable.pause_to_play);
    holder.pauseButton.setEndDrawable(R.drawable.play_to_pause);
    holder.pauseButton.setState((state.stateCode == TorrentStateCode.PAUSED ? MorphButton.MorphState.END
            : MorphButton.MorphState.START));

    if (curOpenTorrent != null && getItemPosition(curOpenTorrent) == position && Utils.isTwoPane(context)) {
        if (!isSelected(position)) {
            Utils.setBackground(holder.itemTorrentList,
                    ContextCompat.getDrawable(context, R.color.accent_light));
        }

        Utils.setBackground(holder.indicatorCurOpenTorrent, ContextCompat.getDrawable(context, R.color.accent));
    }
}

From source file:com.error.hunter.ListenService.java

private void generateBugReport(ActivityManager.ProcessErrorStateInfo entry) {

    String condition;/*from   www  . j  a  v a  2 s  .  c  o  m*/
    badProcess = entry.processName;
    String build = Build.DISPLAY;
    String fingerprint = Build.FINGERPRINT;
    String serial = Build.SERIAL;
    String product = Build.PRODUCT;
    String model = Build.MODEL;

    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    @SuppressWarnings("deprecation")
    long blockSize = stat.getBlockSize();
    @SuppressWarnings("deprecation")
    long availableBlocks = stat.getAvailableBlocks();
    String memory = Formatter.formatFileSize(this, availableBlocks * blockSize).toString();

    MemoryInfo mi = new MemoryInfo();
    ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    activityManager.getMemoryInfo(mi);
    long availableMegs = mi.availMem / 1048576L;

    strBuf.append("Problem detected in: ").append(badProcess);
    if (entry.tag != null) {
        strBuf.append(" (").append(entry.tag).append(")");
    }
    strBuf.append("\nDevice product: " + product);
    strBuf.append("\nDevice model: " + model);
    strBuf.append("\nDevice build: " + build);
    strBuf.append("\nDevice fingerprint: " + fingerprint);
    strBuf.append("\nDevice SN: " + serial);
    strBuf.append("\nDevice available RAM (MB): " + availableMegs);
    strBuf.append("\nDevice free phisical memory: " + memory + "\n");
    strBuf.append(getNetworkInfo());
    strBuf.append("\n");

    ActivityManager actvityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningServiceInfo> procInfos = actvityManager.getRunningServices(1000);
    Iterator<RunningServiceInfo> taskIter = procInfos.iterator();
    RunningServiceInfo info;
    while (taskIter.hasNext()) {
        info = taskIter.next();
        if (info.process.equals(badProcess)) {
            strBuf.append("\nService " + info.service + " crash count: " + info.crashCount + " active since: "
                    + info.activeSince + " process: " + info.process);
        }
    }
    strBuf.append("\n");
    //android.os.Debug.MemoryInfo[] miPid = activityManager.getProcessMemoryInfo(new int[]{entry.pid}); 
    //String memoryProc = miPid[0].toString();
    //strBuf.append("\nRAM used by process (Process: " + entry.processName + " PID: " + entry.pid +"): " + memoryProc + "MB\n");

    switch (entry.condition) {

    case ActivityManager.ProcessErrorStateInfo.CRASHED:
        condition = "CRASHED";
        getDeviceProcessInfo(badProcess, entry.stackTrace);
        writeLogsToFile(condition, badProcess);
        break;
    case ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING:
        condition = "ANR";
        getDeviceProcessInfo(badProcess, "");
        writeLogsToFile(condition, badProcess);
        break;
    default:
        condition = "<unknown>";
        getDeviceProcessInfo(badProcess, entry.stackTrace);
        writeLogsToFile(condition, badProcess);
        break;
    }
}

From source file:org.amahi.anywhere.adapter.ServerFilesAdapter.java

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    final ServerFileViewHolder fileHolder = (ServerFileViewHolder) holder;

    final ServerFile file = filteredFiles.get(position);

    if (Mimes.match(file.getMime()) == Mimes.Type.DIRECTORY) {
        fileHolder.moreInfo.setVisibility(View.GONE);
        fileHolder.moreOptions.setVisibility(View.GONE);

    } else {/*w  ww  .j  av a2 s .  co  m*/
        fileHolder.moreInfo.setVisibility(View.VISIBLE);
        fileHolder.moreOptions.setVisibility(View.VISIBLE);

        if (!isOfflineMode()) {
            fileHolder.fileSize.setText(Formatter.formatFileSize(context, getFileSize(file)));
        } else {
            if (isFileDownloading(fileHolder, file, position)) {
                fileHolder.moreInfo.setVisibility(View.GONE);
                fileHolder.progressBar.setVisibility(View.VISIBLE);
            } else {
                fileHolder.moreInfo.setVisibility(View.VISIBLE);
                fileHolder.progressBar.setVisibility(View.GONE);
                File localFile = new File(context.getFilesDir(),
                        Downloader.OFFLINE_PATH + "/" + file.getName());
                fileHolder.fileSize.setText(Formatter.formatFileSize(context, localFile.length()));
            }
        }

        Date d = getLastModified(file);
        SimpleDateFormat dt = new SimpleDateFormat("EEE LLL dd yyyy", Locale.getDefault());
        fileHolder.fileLastModified.setText(dt.format(d));
    }

    SpannableStringBuilder sb = new SpannableStringBuilder(file.getName());
    if (queryString != null && !TextUtils.isEmpty(queryString)) {
        int searchMatchPosition = file.getName().toLowerCase().indexOf(queryString.toLowerCase());
        if (searchMatchPosition != -1)
            sb.setSpan(fcs, searchMatchPosition, searchMatchPosition + queryString.length(),
                    Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    }
    fileHolder.fileTextView.setText(sb);

    if (Mimes.match(file.getMime()) == Mimes.Type.IMAGE) {
        setUpImageIcon(file, fileHolder.fileIconView);
    } else if (Mimes.match(file.getMime()) == Mimes.Type.AUDIO) {
        setUpAudioArt(file, fileHolder.fileIconView);
    } else {
        fileHolder.fileIconView.setImageResource(Mimes.getFileIcon(file));
    }

    fileHolder.itemView.setOnClickListener(view -> {
        mListener.onItemClick(fileHolder.itemView, fileHolder.getAdapterPosition());
    });

    fileHolder.moreOptions.setOnClickListener(view -> {
        selectedPosition = fileHolder.getAdapterPosition();
        mListener.onMoreOptionClick(fileHolder.itemView, fileHolder.getAdapterPosition());
    });
}

From source file:com.giovanniterlingen.windesheim.controllers.DownloadController.java

@Override
protected String doInBackground(final String... strings) {
    try {/*  w  w  w .j a v a2s .  c o  m*/
        activeDownloads.put(contentId, new Download());
        int lastSlash = url.lastIndexOf('/');
        String fileName = url.substring(lastSlash + 1);

        File directory = Environment.getExternalStoragePublicDirectory(
                ApplicationLoader.applicationContext.getResources().getString(R.string.app_name));
        if (!directory.exists()) {
            directory.mkdirs();
        }

        final String encodedUrl = new URI("https", "elo.windesheim.nl", url, null).toString();

        downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(encodedUrl));
        request.addRequestHeader("Cookie", new CookieController().getNatSchoolCookie()).setTitle(fileName)
                .setDescription(activity.getResources().getString(R.string.downloading))
                .setDestinationInExternalPublicDir(File.separator
                        + ApplicationLoader.applicationContext.getResources().getString(R.string.app_name),
                        fileName);

        currentDownloadId = downloadManager.enqueue(request);
        while (true) {
            if (isCancelled()) {
                return "cancelled";
            }
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(currentDownloadId);
            Cursor cursor = downloadManager.query(query);
            if (cursor.getCount() == 0) {
                return "cancelled";
            }
            cursor.moveToFirst();
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            if (status == DownloadManager.STATUS_SUCCESSFUL || status == DownloadManager.STATUS_FAILED) {
                break;
            }
            if (status == DownloadManager.STATUS_PAUSED || status == DownloadManager.STATUS_PENDING) {
                // paused, reset download state to pending
                activeDownloads.put(contentId, new Download());
                NotificationCenter.getInstance().postNotificationName(NotificationCenter.downloadPending,
                        studyRouteId, adapterPosition, contentId);
                Thread.sleep(100);
                continue;
            }
            long downloaded = cursor
                    .getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
            long total = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
            cursor.close();
            if (total > 0 && downloaded > 0) {
                int progress = (int) (downloaded * 100 / total);
                String s = Formatter.formatFileSize(activity, downloaded) + "/"
                        + Formatter.formatFileSize(activity, total);
                activeDownloads.get(contentId).setProgress(progress);
                activeDownloads.get(contentId).setProgressString(s);
                publishProgress(progress, s);
            }
            Thread.sleep(100);
        }
        return new File(directory, fileName).getAbsolutePath();
    } catch (SecurityException e) {
        return "permission";
    } catch (Exception e) {
        return null;
    }
}

From source file:org.proninyaroslav.libretorrent.fragments.AddTorrentInfoFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_add_torrent_info, container, false);

    torrentNameField = (EditText) v.findViewById(R.id.torrent_name);
    layoutTorrentName = (TextInputLayout) v.findViewById(R.id.layout_torrent_name);
    sha1HashView = (TextView) v.findViewById(R.id.torrent_hash_sum);
    commentView = (TextView) v.findViewById(R.id.torrent_comment);
    createdByView = (TextView) v.findViewById(R.id.torrent_created_in_program);
    torrentSizeView = (TextView) v.findViewById(R.id.torrent_size);
    fileCountView = (TextView) v.findViewById(R.id.torrent_file_count);
    creationDateView = (TextView) v.findViewById(R.id.torrent_create_date);
    pathToUploadView = (TextView) v.findViewById(R.id.upload_torrent_into);
    folderChooserButton = (ImageButton) v.findViewById(R.id.folder_chooser_button);
    sequentialDownload = (CheckBox) v.findViewById(R.id.sequential_download);
    startTorrent = (CheckBox) v.findViewById(R.id.start_torrent);
    freeSpace = (TextView) v.findViewById(R.id.free_space);

    TorrentMetaInfo info = getArguments().getParcelable(TAG_INFO);

    if (info != null) {
        torrentNameField.setText(info.getTorrentName());
        sha1HashView.setText(info.getSha1Hash());
        if (TextUtils.isEmpty(info.getComment())) {
            commentView.setVisibility(View.GONE);

            LinearLayout commentViewLayout = (LinearLayout) v.findViewById(R.id.layout_torrent_comment);
            commentViewLayout.setVisibility(View.GONE);

            TextView commentViewHeader = (TextView) v.findViewById(R.id.header_torrent_comment);
            commentViewHeader.setVisibility(View.GONE);
        } else {//from  w  w  w. jav  a  2s .c o  m
            commentView.setText(info.getComment());
        }
        if (TextUtils.isEmpty(info.getCreatedBy())) {
            createdByView.setVisibility(View.GONE);

            LinearLayout createdByViewLayout = (LinearLayout) v
                    .findViewById(R.id.layout_torrent_created_in_program);
            createdByViewLayout.setVisibility(View.GONE);

            TextView createdByViewHeader = (TextView) v.findViewById(R.id.header_torrent_created_in_program);
            createdByViewHeader.setVisibility(View.GONE);
        } else {
            createdByView.setText(info.getCreatedBy());
        }
        torrentSizeView.setText(Formatter.formatFileSize(activity, info.getTorrentSize()));
        creationDateView
                .setText(SimpleDateFormat.getDateTimeInstance().format(new Date(info.getCreationDate())));
        fileCountView.setText(Integer.toString(info.getFileCount()));
        pathToUploadView.setText(downloadDir);
        freeSpace.setText(String.format(getString(R.string.free_space), Formatter
                .formatFileSize(activity.getApplicationContext(), FileIOUtils.getFreeSpace(downloadDir))));
    }

    startTorrent.setChecked(true);

    return v;
}

From source file:org.proninyaroslav.libretorrent.fragments.AddTorrentFilesFragment.java

@Override
public void onItemCheckedChanged(BencodeFileTree node, boolean selected) {
    node.select(selected);/*from w w  w .j a va2 s  .co m*/

    filesSize.setText(String.format(getString(R.string.files_size),
            Formatter.formatFileSize(activity.getApplicationContext(), fileTree.selectedFileSize()),
            Formatter.formatFileSize(activity.getApplicationContext(), fileTree.size())));
}

From source file:org.proninyaroslav.libretorrent.fragments.DetailTorrentInfoFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_detail_torrent_info, container, false);

    torrentNameField = (EditText) v.findViewById(R.id.torrent_name);
    layoutTorrentName = (TextInputLayout) v.findViewById(R.id.layout_torrent_name);
    sha1HashView = (TextView) v.findViewById(R.id.torrent_hash_sum);
    commentView = (TextView) v.findViewById(R.id.torrent_comment);
    createdByView = (TextView) v.findViewById(R.id.torrent_created_in_program);
    torrentSizeView = (TextView) v.findViewById(R.id.torrent_size);
    fileCountView = (TextView) v.findViewById(R.id.torrent_file_count);
    creationDateView = (TextView) v.findViewById(R.id.torrent_create_date);
    pathToUploadView = (TextView) v.findViewById(R.id.upload_torrent_into);
    folderChooserButton = (ImageButton) v.findViewById(R.id.folder_chooser_button);
    sequentialDownload = (CheckBox) v.findViewById(R.id.sequential_download);
    freeSpace = (TextView) v.findViewById(R.id.free_space);
    sequentialDownload.setOnClickListener(new View.OnClickListener() {
        @Override//from  w w  w  . j av a 2  s .  co  m
        public void onClick(View view) {

            if (callback != null) {
                callback.onTorrentInfoChanged();
            }
        }
    });

    Torrent torrent = getArguments().getParcelable(TAG_TORRENT);
    TorrentMetaInfo info = getArguments().getParcelable(TAG_INFO);

    if (info != null && torrent != null) {
        torrentNameField.setText(torrent.getName());
        sha1HashView.setText(info.getSha1Hash());
        if (TextUtils.isEmpty(info.getComment())) {
            commentView.setVisibility(View.GONE);

            LinearLayout commentViewLayout = (LinearLayout) v.findViewById(R.id.layout_torrent_comment);
            commentViewLayout.setVisibility(View.GONE);

            TextView commentViewHeader = (TextView) v.findViewById(R.id.header_torrent_comment);
            commentViewHeader.setVisibility(View.GONE);
        } else {
            commentView.setText(info.getComment());
        }
        if (TextUtils.isEmpty(info.getCreatedBy())) {
            createdByView.setVisibility(View.GONE);

            LinearLayout createdByViewLayout = (LinearLayout) v
                    .findViewById(R.id.layout_torrent_created_in_program);
            createdByViewLayout.setVisibility(View.GONE);

            TextView createdByViewHeader = (TextView) v.findViewById(R.id.header_torrent_created_in_program);
            createdByViewHeader.setVisibility(View.GONE);
        } else {
            createdByView.setText(info.getCreatedBy());
        }
        torrentSizeView.setText(Formatter.formatFileSize(activity, info.getTorrentSize()));
        creationDateView
                .setText(SimpleDateFormat.getDateTimeInstance().format(new Date(info.getCreationDate())));
        fileCountView.setText(Integer.toString(info.getFileCount()));
        pathToUploadView.setText(torrent.getDownloadPath());
        sequentialDownload.setChecked(torrent.isSequentialDownload());
        freeSpace.setText(String.format(getString(R.string.free_space), Formatter.formatFileSize(
                activity.getApplicationContext(), FileIOUtils.getFreeSpace(torrent.getDownloadPath()))));
    }

    return v;
}

From source file:org.droid2droid.install.DownloadApkActivity.java

private void setDialog(Intent intent) {
    int id = intent.getIntExtra(Notifications.EXTRA_ID, -1);
    DownloadFile df = mTransInfo = AbstractSrvRemoteAndroid.getDowloadFile(id);
    Log.d(TAG_INSTALL, PREFIX_LOG + "setDialog intent=" + System.identityHashCode(intent) + " id=" + id);
    assert df != null;
    if (df == null) {
        if (E)/*from  w ww  .j  a  v  a  2s  . c  o  m*/
            Log.e(TAG_INSTALL, PREFIX_LOG + "ERROR phatom id " + id + " when want to open DownloadApkActivity");
        return;
    }

    mLine1.setText(getString(R.string.download_line1, df.from));
    mLine2.setText(getString(R.string.download_line2, df.label));
    mLine3.setText(getString(R.string.download_line3, Formatter.formatFileSize(this, df.size)));
    mLine5.setText(getString(R.string.download_line5));
    onProgressUpdate();
}