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:com.amaze.carbonfilemanager.services.ExtractService.java

private void publishResults(int id, String fileName, int sourceFiles, int sourceProgress, long total, long done,
        int speed, boolean isCompleted) {
    if (!progressHandler.getCancelled()) {
        mBuilder.setContentTitle(getResources().getString(R.string.extracting));
        float progressPercent = ((float) done / total) * 100;
        mBuilder.setProgress(100, Math.round(progressPercent), false);
        mBuilder.setOngoing(true);//from www .j  av  a 2 s .c  o m
        mBuilder.setContentText(fileName + " " + Formatter.formatFileSize(cd, done) + "/"
                + Formatter.formatFileSize(cd, total));
        int id1 = Integer.parseInt("123" + id);
        mNotifyManager.notify(id1, mBuilder.build());
        if (progressPercent == 100 || total == 0) {
            mBuilder.setContentTitle(getString(R.string.extract_complete));
            mBuilder.setContentText(fileName + " " + Formatter.formatFileSize(cd, total));
            mBuilder.setProgress(100, 100, false);
            mBuilder.setOngoing(false);
            mNotifyManager.notify(id1, mBuilder.build());
            publishCompletedResult("", id1);
        }

        DataPackage intent = new DataPackage();
        intent.setName(fileName);
        intent.setSourceFiles(sourceFiles);
        intent.setSourceProgress(sourceProgress);
        intent.setTotal(total);
        intent.setByteProgress(done);
        intent.setSpeedRaw(speed);
        intent.setMove(false);
        intent.setCompleted(isCompleted);
        putDataPackage(intent);

        if (progressListener != null) {
            progressListener.onUpdate(intent);
            if (isCompleted)
                progressListener.refresh();
        }
    } else
        publishCompletedResult(fileName, Integer.parseInt("123" + id));
}

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

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    if (activity == null) {
        activity = (AppCompatActivity) getActivity();
    }/* w ww .  j  av  a2 s . c  o m*/

    if (savedInstanceState != null) {
        fileTree = (TorrentContentFileTree) savedInstanceState.getSerializable(TAG_FILE_TREE);
        curDir = (TorrentContentFileTree) savedInstanceState.getSerializable(TAG_CUR_DIR);

    } else {
        ArrayList<BencodeFileItem> files = getArguments().getParcelableArrayList(TAG_FILES);
        ArrayList<Priority> priorities = (ArrayList<Priority>) getArguments().getSerializable(TAG_PRIORITIES);

        if ((files == null || priorities == null) || files.size() != priorities.size()) {
            return;
        }

        fileTree = TorrentContentFileTreeUtils.buildFileTree(files);

        FileTreeDepthFirstSearch<TorrentContentFileTree> search = new FileTreeDepthFirstSearch<TorrentContentFileTree>();

        /* Set priority for selected files */
        for (int i = 0; i < files.size(); i++) {
            if (priorities.get(i) != Priority.IGNORE) {
                BencodeFileItem f = files.get(i);

                TorrentContentFileTree file = search.find(fileTree, f.getIndex());
                if (file != null) {
                    file.setPriority(priorities.get(i));
                    /*
                     * Disable the ability to select the file
                     * because it's being downloaded/download
                     */
                    file.select(TorrentContentFileTree.SelectState.DISABLED);
                }
            }
        }

        /* Is assigned the root dir of the file tree */
        curDir = fileTree;
    }

    filesSize = (TextView) activity.findViewById(R.id.files_size);
    if (filesSize != null) {
        filesSize.setText(String.format(getString(R.string.files_size),
                Formatter.formatFileSize(activity.getApplicationContext(), fileTree.selectedFileSize()),
                Formatter.formatFileSize(activity.getApplicationContext(), fileTree.size())));
    }

    fileList = (RecyclerView) activity.findViewById(R.id.file_list);

    if (fileList != null) {
        layoutManager = new LinearLayoutManager(activity);
        fileList.setLayoutManager(layoutManager);
        /*
         * A RecyclerView by default creates another copy of the ViewHolder in order to
         * fade the views into each other. This causes the problem because the old ViewHolder gets
         * the payload but then the new one doesn't. So needs to explicitly tell it to reuse the old one.
         */
        DefaultItemAnimator animator = new DefaultItemAnimator() {
            @Override
            public boolean canReuseUpdatedViewHolder(RecyclerView.ViewHolder viewHolder) {
                return true;
            }
        };
        fileList.setItemAnimator(animator);
        adapter = new TorrentContentFilesAdapter(getChildren(curDir), activity,
                R.layout.item_torrent_content_file, this);

        fileList.setAdapter(adapter);
    }

    if (savedInstanceState != null) {
        selectedFiles = savedInstanceState.getStringArrayList(TAG_SELECTED_FILES);
        if (savedInstanceState.getBoolean(TAG_IN_ACTION_MODE, false)) {
            actionMode = activity.startActionMode(actionModeCallback);
            adapter.setSelectedItems(savedInstanceState.getIntegerArrayList(TAG_SELECTABLE_ADAPTER));
            actionMode.setTitle(String.valueOf(adapter.getSelectedItemCount()));
        }
    }
}

From source file:de.aw.awlib.fragments.AWRemoteFileChooser.java

@Override
public void onBindViewHolder(AWLibViewHolder holder, FTPFile file, int position) {
    TextView tv;/*from   ww w. ja  v a  2  s. com*/
    switch (holder.getItemViewType()) {
    case BACKTOPARENT:
        for (int resID : viewResIDs) {
            View view = holder.itemView.findViewById(resID);
            if (resID == R.id.folderImage) {
                ImageView img = (ImageView) view;
                img.setImageResource(R.drawable.ic_open_folder);
            } else if (resID == R.id.awlib_fileName) {
                tv = (TextView) view;
                if (mDirectoyList.size() == 0) {
                    tv.setText(".");
                } else {
                    tv.setText(file.getName());
                }
            } else if (resID == R.id.awlib_fileData) {
                view.setVisibility(View.GONE);
            }
        }
        break;
    default:
        for (int resID : viewResIDs) {
            View view = holder.itemView.findViewById(resID);
            if (resID == R.id.folderImage) {
                ImageView img = (ImageView) view;
                if (file.isDirectory()) {
                    img.setImageResource(R.drawable.ic_closed_folder);
                } else {
                    img.setImageResource(R.drawable.ic_file_generic);
                }
            } else if (resID == R.id.awlib_fileName) {
                tv = (TextView) view;
                tv.setText(file.getName());
            } else if (resID == R.id.awlib_fileData) {
                view.setVisibility(View.VISIBLE);
                tv = (TextView) view;
                tv.setText(Formatter.formatFileSize(getContext(), file.getSize()));
            }
        }
    }
}

From source file:com.lzy.demo.okrx2.RxFileDownloadActivity.java

@OnClick(R.id.fileDownload2)
public void fileDownload2(View view) {
    Observable.create(new ObservableOnSubscribe<Progress>() {
        @Override//from  ww  w  .  j  a v  a  2  s.com
        public void subscribe(@NonNull final ObservableEmitter<Progress> e) throws Exception {
            String etString = etUrl.getText().toString();
            String url = TextUtils.isEmpty(etString) ? Urls.URL_DOWNLOAD : etString;
            OkGo.<File>get(url)//
                    .headers("aaa", "111")//
                    .params("bbb", "222")//
                    .execute(new FileCallback() {
                        @Override
                        public void onSuccess(Response<File> response) {
                            e.onComplete();
                        }

                        @Override
                        public void onError(Response<File> response) {
                            e.onError(response.getException());
                        }

                        @Override
                        public void downloadProgress(Progress progress) {
                            e.onNext(progress);
                        }
                    });
        }
    })//
            .doOnSubscribe(new Consumer<Disposable>() {
                @Override
                public void accept(@NonNull Disposable disposable) throws Exception {
                    btnFileDownload2.setText("...");
                }
            })//
            .observeOn(AndroidSchedulers.mainThread())//
            .subscribe(new Observer<Progress>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                    addDisposable(d);
                }

                @Override
                public void onNext(@NonNull Progress progress) {
                    String downloadLength = Formatter.formatFileSize(getApplicationContext(),
                            progress.currentSize);
                    String totalLength = Formatter.formatFileSize(getApplicationContext(), progress.totalSize);
                    tvDownloadSize.setText(downloadLength + "/" + totalLength);
                    String speed = Formatter.formatFileSize(getApplicationContext(), progress.speed);
                    tvNetSpeed.setText(String.format("%s/s", speed));
                    tvProgress.setText(numberFormat.format(progress.fraction));
                    pbProgress.setMax(10000);
                    pbProgress.setProgress((int) (progress.fraction * 10000));
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    e.printStackTrace();
                    btnFileDownload2.setText("");
                    showToast(e.getMessage());
                }

                @Override
                public void onComplete() {
                    btnFileDownload2.setText("?");
                }
            });
}

From source file:com.doomy.padlock.InfoFragment.java

/**
  * Gets available internal memory size.
  *//from  ww  w  .j  a  v  a  2s .  c o m
  * @return The size of internal storage available.
  */
public String getAvailableInternalMemorySize() {
    File mPath = Environment.getDataDirectory();
    StatFs mStat = new StatFs(mPath.getPath());
    long mBlockSize = mStat.getBlockSize();
    long mAvailableBlocks = mStat.getAvailableBlocks();
    return Formatter.formatFileSize(getActivity(), mAvailableBlocks * mBlockSize);
}

From source file:de.aw.awlib.fragments.AWFileChooser.java

@Override
public void onBindViewHolder(AWLibViewHolder holder, File file, int position) {
    TextView tv;//from   w w w  .ja  v  a 2 s .c o  m
    switch (holder.getItemViewType()) {
    case HASPARENTFOLDER:
        for (int resID : viewResIDs) {
            View view = holder.itemView.findViewById(resID);
            if (resID == R.id.folderImage) {
                ImageView img = (ImageView) view;
                img.setImageResource(R.drawable.ic_open_folder);
            } else if (resID == R.id.awlib_fileName) {
                tv = (TextView) view;
                tv.setText("..");
            } else if (resID == R.id.awlib_fileData) {
                tv = (TextView) view;
                tv.setText(file.getAbsolutePath());
            }
        }
        break;
    default:
        for (int resID : viewResIDs) {
            View view = holder.itemView.findViewById(resID);
            if (resID == R.id.folderImage) {
                ImageView img = (ImageView) view;
                if (file.isDirectory()) {
                    img.setImageResource(R.drawable.ic_closed_folder);
                } else {
                    img.setImageResource(R.drawable.ic_file_generic);
                }
            } else if (resID == R.id.awlib_fileName) {
                tv = (TextView) view;
                tv.setText(file.getName());
            } else if (resID == R.id.awlib_fileData) {
                tv = (TextView) view;
                tv.setText(Formatter.formatFileSize(getContext(), file.length()));
            }
        }
    }
}

From source file:com.doomy.padlock.InfoFragment.java

/**
  * Gets total internal memory size.//w  ww.  j  a  v a 2  s  .  c o m
  *
  * @return The total size of internal storage.
  */
public String getTotalInternalMemorySize() {
    File mPath = Environment.getDataDirectory();
    StatFs mStat = new StatFs(mPath.getPath());
    long mBlockSize = mStat.getBlockSize();
    long mTotalBlocks = mStat.getBlockCount();
    return Formatter.formatFileSize(getActivity(), mTotalBlocks * mBlockSize);
}

From source file:com.amaze.filemanager.asynchronous.asynctasks.LoadFilesListTask.java

private LayoutElementParcelable createListParcelables(HybridFileParcelable baseFile) {
    if (!dataUtils.isFileHidden(baseFile.getPath())) {
        String size = "";
        long longSize = 0;

        if (baseFile.isDirectory()) {
            ma.folder_count++;// w ww  .j  ava  2s.c  om
        } else {
            if (baseFile.getSize() != -1) {
                try {
                    longSize = baseFile.getSize();
                    size = Formatter.formatFileSize(c, longSize);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }

            ma.file_count++;
        }

        LayoutElementParcelable layoutElement = new LayoutElementParcelable(baseFile.getName(),
                baseFile.getPath(), baseFile.getPermission(), baseFile.getLink(), size, longSize, false,
                baseFile.getDate() + "", baseFile.isDirectory(), showThumbs, baseFile.getMode());
        return layoutElement;
    }

    return null;
}

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

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == DIR_CHOOSER_REQUEST) {
        if (resultCode == Activity.RESULT_OK) {
            if (data.hasExtra(FileManagerDialog.TAG_RETURNED_PATH)) {
                downloadDir = data.getStringExtra(FileManagerDialog.TAG_RETURNED_PATH);
                pathToUploadView.setText(downloadDir);
                freeSpace.setText(String.format(getString(R.string.free_space), Formatter.formatFileSize(
                        activity.getApplicationContext(), FileIOUtils.getFreeSpace(downloadDir))));
            }//from www  .  j av  a 2 s  .co m
        }
    }
}

From source file:com.amaze.filemanager.fragments.ProcessViewerFragment.java

public void processResults(final DatapointParcelable dataPackage, int serviceType) {
    if (dataPackage != null) {
        String name = dataPackage.name;
        long total = dataPackage.totalSize;
        long doneBytes = dataPackage.byteProgress;
        boolean move = dataPackage.move;

        if (!isInitialized) {

            // initializing views for the first time
            chartInit(total);/*from w  w w.jav a  2 s .c o  m*/

            // setting progress image
            setupDrawables(serviceType, move);
            isInitialized = true;
        }

        addEntry(FileUtils.readableFileSizeFloat(doneBytes),
                FileUtils.readableFileSizeFloat(dataPackage.speedRaw));

        mProgressFileNameText.setText(name);

        Spanned bytesText = Html.fromHtml(getResources().getString(R.string.written) + " <font color='"
                + accentColor + "'><i>" + Formatter.formatFileSize(getContext(), doneBytes) + " </font></i>"
                + getResources().getString(R.string.out_of) + " <i>"
                + Formatter.formatFileSize(getContext(), total) + "</i>");
        mProgressBytesText.setText(bytesText);

        Spanned fileProcessedSpan = Html.fromHtml(getResources().getString(R.string.processing_file)
                + " <font color='" + accentColor + "'><i>" + (dataPackage.sourceProgress) + " </font></i>"
                + getResources().getString(R.string.of) + " <i>" + dataPackage.sourceFiles + "</i>");
        mProgressFileText.setText(fileProcessedSpan);

        Spanned speedSpan = Html.fromHtml(
                getResources().getString(R.string.current_speed) + ": <font color='" + accentColor + "'><i>"
                        + Formatter.formatFileSize(getContext(), dataPackage.speedRaw) + "/s</font></i>");
        mProgressSpeedText.setText(speedSpan);

        Spanned timerSpan = Html.fromHtml(getResources().getString(R.string.service_timer) + ": <font color='"
                + accentColor + "'><i>" + Utils.formatTimer(++looseTimeInSeconds) + "</font></i>");

        mProgressTimer.setText(timerSpan);

        if (dataPackage.completed)
            mCancelButton.setVisibility(View.GONE);
    }
}