Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android can't get the file size from dialog

Tags:

android

dialog

I have the following method to determine the file size:

    public static long getSize(String path) {

    File file = new File(path);

    if (file.exists()) {
        long size = file.length();

        return size;
    } else {
        Log.e("zero size", "the file size is zero!");
        return 0;

    }

Now I want to show a dialog with the following method (the code IS NOT complete):

 public void gimmeDialog(String path_to_file) {

    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.dialog);
    dialog.setTitle("Confirm");

    TextView text = (TextView) dialog.findViewById(R.id.txtUploadInfo);

    Button dialogButtonOK = (Button) dialog.findViewById(R.id.btnDialogOK);

    long uploadSize = Send.getSize(path_to_file) / 1024 / 1024;

    text.setText("You are about to upload "
            + Long.toString(uploadSize)
            + " MB. You must accept the terms of service before you can proceed");

    dialogButtonOK.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    dialog.show();
}

The problem is that uploadSize is always zero, though the method getSize() returns correct file size when called outside the dialog function. The given string path IS correct. What can be the reason?

P.S. Send is my class name

like image 549
Droidman Avatar asked Dec 20 '12 12:12

Droidman


2 Answers

You are making a integer division and if the numenator is smaller than the denominator the result is 0.

Try with a double division:

double uploadSize = 1.0 * Send.getSize(path_to_file) / 1024 / 1024;
like image 79
Narkha Avatar answered Sep 27 '22 16:09

Narkha


Call getSize() and set a variable outside of the dialog function, which is accessible inside the dialog function. Or pass it as a variable to the function.

That doesn't really explain the problem, but it does solve it.

like image 41
breadbin Avatar answered Sep 27 '22 18:09

breadbin